简体   繁体   English

Javascript在字符串中的第n个位置插入空格

[英]Javascript insert space at nth position in string

Let's say I have the following string: "Stackoverflow", and I want to insert a space between every third number like this: "S tac kov erf low" starting from the end.假设我有以下字符串:“Stackoverflow”,我想在每三个数字之间插入一个空格,如下所示:“S tac kov erf low”从末尾开始。 Can this be done with regexes?这可以用正则表达式完成吗?

I have done it the following way with a for-loop now:我现在用 for 循环按以下方式完成了它:

var splitChars = (inputString: string) => {
    let ret = [];
    let counter = 0;
    for(let i = inputString.length; i >= 0;  i --) {
       if(counter < 4) ret.unshift(inputString.charAt(i));
       if(counter > 3){
        ret.unshift(" ");
        counter = 0;
        ret.unshift(inputString.charAt(i));
        counter ++;
       } 
       counter ++;
    }
    return ret;
}

Can I shorten this is some way?我可以以某种方式缩短吗?

您可以积极向前看并添加空格。

 console.log("StackOverflow".replace(/.{1,3}(?=(.{3})+$)/g, '$& '));

You can use Regex to chunk it up and then join it back together with a string.您可以使用 Regex 将其分块,然后将其与字符串连接在一起。

 var string = "StackOverflow"; var chunk_size = 3; var insert = ' '; // Reverse it so you can start at the end string = string.split('').reverse().join(''); // Create a regex to split the string const regex = new RegExp('.{1,' + chunk_size + '}', 'g'); // Chunk up the string and rejoin it string = string.match(regex).join(insert); // Reverse it again string = string.split('').reverse().join(''); console.log(string);

This is a solution without regexp, with a for...of这是一个没有正则表达式的解决方案,带有 for...of

 <!DOCTYPE html> <html> <body> <script> const x="Stackoverflow",result=[]; let remaind = x.length %3 , ind=0 , val; for(const i of x){ val = (++ind % 3 === remaind) ? i+" " : i; result.push(val); } console.log(result.join('')); </script> </body> </html>

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

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