简体   繁体   English

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

[英]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".我有一个字符串,例如“8FPHFW08”,我想获取这些子字符串:“8F000000”、“00PH0000”、“0000FW00”、“00000008”。

The relative python fuction is this:相对的 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 

This is my attempt but I need 0 in empty positions这是我的尝试,但我需要 0 在空位

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?我怎样才能在 Javascript 中做同样的事情?

JavaScript strings are immutable, so there's no fancy shortcut for "overwrite a substring with another substring". JavaScript 字符串是不可变的,因此“用另一个子字符串覆盖 substring”没有花哨的快捷方式。 You have to slice it up yourself.你必须自己slice

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;

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:不确定这是学习一门新语言的最佳方式,但我尝试为您提供 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'))

Use slice to get the partial string.使用slice获取部分字符串。 Use padStart and padEnd fill the start and end with 0使用padStartpadEnd0填充开始和结束

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM