Reputation:
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?
Upvotes: 5
Views: 1828
Reputation: 386604
You could take a positive lookahead and add spaces.
console.log("StackOverflow".replace(/.{1,3}(?=(.{3})+$)/g, '$& '));
Upvotes: 7
Reputation: 1629
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>
Upvotes: 0
Reputation: 23379
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);
Upvotes: 4