admin管理员组文章数量:1323157
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. Can this be done with regexes?
I have done it the following way with a for-loop now:
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?
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. Can this be done with regexes?
I have done it the following way with a for-loop now:
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?
Share asked Aug 27, 2020 at 14:19 user12067722user120677223 Answers
Reset to default 7You could take a positive lookahead and add spaces.
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.
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
<!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>
本文标签: Javascript insert space at nth position in stringStack Overflow
版权声明:本文标题:Javascript insert space at nth position in string - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742142229a2422631.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论