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

5
假设我有以下字符串: "Stackoverflow",我想在每个第三个数字之间插入一个空格,如下所示: "S tac kov erf low" 从末尾开始。这可以使用正则表达式完成吗?
我现在已经通过for-loop这种方式做到了:
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;
}

我能用一些方法来缩短这个吗?

3个回答

7

你可以使用正向预查并添加空格。

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


1
我可以问一下你的正则表达式中 + 是如何起作用的吗?我理解它是在 (.{3}) 上“起作用”。如果是这样,那么我认为 (.{3})+ 的意思是查找 ..................(基本上是以 3 个点为倍数的 .)。 - tonitone120
1
是的,它是一个量词符号,表示从当前字符一直到字符串末尾的所有字符。 - Nina Scholz
1
谢谢。我花了一些时间才明白,因为我们是在“倒推”!也就是说,如果任务是在每三个字符后(从左到右)加一个空格,那就更容易了,对吧? - tonitone120

4
你可以使用正则表达式将其分块,然后用字符串重新连接起来。

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


0

这是一种不使用正则表达式的解决方案,采用 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>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接