[英]Javascript insert space at nth position in string
假设我有以下字符串:“Stackoverflow”,我想在每三个数字之间插入一个空格,如下所示:“S tac kov erf low”从末尾开始。 这可以用正则表达式完成吗?
我现在用 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;
}
我可以以某种方式缩短吗?
您可以积极向前看并添加空格。
console.log("StackOverflow".replace(/.{1,3}(?=(.{3})+$)/g, '$& '));
您可以使用 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);
这是一个没有正则表达式的解决方案,带有 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.