Manux
Manux

Reputation: 3

Split string to equal length substrings in javascript

I have a string, for example "8FPHFW08" and I want to get these substrings: "8F000000", "00PH0000","0000FW00" , "00000008".

The relative python fuction is this:

def split_str(s):
    res = []
    for i in range(0,len(s),2):
        a = ['0']*len(s)
        a[i:i+2] = s[i:i+2]
        res.append("".join(a))
    return res 

This is my attempt but I need 0 in empty positions

function split_olc(olc) {   
    var splitted = []
    splitted.push(olc.match(/(..?)/g))
    console.log(splitted[0])
    return splitted[0]

}

How can I do the same thing in Javascript?

Upvotes: 0

Views: 229

Answers (3)

adiga
adiga

Reputation: 35259

Use slice to get the partial string. Use padStart and padEnd fill the start and end with 0

function replace(str) {
  const len = str.length,
        output = []
        
  for (let i = 0; i < len; i += 2) {
    output.push(
      str.slice(i, i+2)
          .padStart(i+2, '0')
          .padEnd(len, '0')
    )
  }

  return output
}

console.log(
  ...replace("8FPHFW08")
)

Upvotes: 1

user3282374
user3282374

Reputation:

Not sure this is the best way to learn a new language, but I've tried to give you the best one-for-one translation of python to js of your code:

function split_str(s) {                          // def split_str(s):
    const res = []                               // res = []
    for (let i = 0; i < s.length; i += 2) {      // for i in range(0,len(s),2):
        const a = new Array(s.length).fill('0'); //   a = ['0']*len(s)
        a.splice(i, 2, s[i], s[i+1]);            //   a[i:i+2] = s[i:i+2]
        res.push(a.join(''));                    //   res.append("".join(a))
    }
    return res;                                  // return res 
}

console.log(split_str('helloworld'))

Upvotes: 2

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324820

JavaScript strings are immutable, so there's no fancy shortcut for "overwrite a substring with another substring". You have to slice it up yourself.

Start with a "template", a string of the appropriate length with all zeroes, then splice it and your subject string appropriately.

const template = s.replace(/./g,'0');
const res = [];
for( let i=0; i<s.length; i+=2) {
    res.push(
        template.substring(0, i)
        + s.substring(i, i+2)
        + template.substring(i+2)
    );
}
return res;

Upvotes: 2

Related Questions