5

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?

3 Answers 3

7

You could take a positive lookahead and add spaces.

console.log("StackOverflow".replace(/.{1,3}(?=(.{3})+$)/g, '$& '));

Sign up to request clarification or add additional context in comments.

3 Comments

Can I ask how the + is acting in your regexp? I interpret it as 'acting on' (.{3}). If so, I see (.{3})+ as meaning 'look for' ... or ...... or ......... (basically . in multiples of 3).
yes it is a quantifier for the following characters until the end of string.
Thanks. Took me a while to get it because we're working 'backwards'! I.e. if the job was to put a space after every three characters (from left-to-right) that would've been easier, right?
4

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);

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.