在 javascript 中将字符串拆分为等长子字符串

Split string to equal length substrings in javascript

我有一个字符串,例如“8FPHFW08”,我想获取这些子字符串:“8F000000”、“00PH0000”、“0000FW00”、“00000008”。

相对的python函数是这样的:

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 

这是我的尝试,但我需要 0 个空位置

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

}

如何在 Javascript 中做同样的事情?

JavaScript 字符串是不可变的,因此“用另一个子字符串覆盖一个子字符串”没有奇特的快捷方式。你必须 slice 自己搞定。

从一个“模板”开始,一个长度合适且全为零的字符串,然后将它和您的主题字符串适当地拼接起来。

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;

不确定这是学习一门新语言的最佳方式,但我已尝试为您提供最好的一对一翻译 python 到您的代码的 js:

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'))

使用slice获取部分字符串。使用padStart and padEnd 开始和结束用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")
)