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?
To add a space between the characters of a string, call the split() method on the string to get an array of characters, and call the join() method on the array to join the substrings with a space separator, e.g. str. split(''). join(' ') . Copied!
To insert a character after every N characters, call the replace() method on the string, passing it the following regular expression - str. replace(/. {2}/g, '$&c') . The replace method will replace every 2 characters with the characters plus the provided replacement.
The newline character is \n in JavaScript and many other languages. All you need to do is add \n character whenever you require a line break to add a new line to a string.
Use the padEnd() and padStart() methods to add spaces to the end or beginning of a string, e.g. str. padEnd(6, ' '); . The methods take the maximum length of the new string and the fill string and return the padded string. Copied!
You could take a positive lookahead and add spaces.
console.log("StackOverflow".replace(/.{1,3}(?=(.{3})+$)/g, '$& '));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With