Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript insert space at nth position in string

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?

like image 593
newbie Avatar asked Aug 27 '20 14:08

newbie


People also ask

How do you put a space in a string in JavaScript?

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!

How can I insert a character after every n characters in JavaScript?

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.

Can we use \n in JavaScript?

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.

How do you leave a space in JavaScript?

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!


1 Answers

You could take a positive lookahead and add spaces.

console.log("StackOverflow".replace(/.{1,3}(?=(.{3})+$)/g, '$& '));
like image 148
Nina Scholz Avatar answered Nov 15 '22 05:11

Nina Scholz