0

I would like to add comma after every third character of the string.

I tried Adding comma after some character in string

I also tried using regex

"The quick brown fox jumps over the lazy dogs.".replace(/(.{3})/g,",")

But didn't work for me.

surazzarus
  • 702
  • 2
  • 15
  • 31

3 Answers3

0

Your problem is that you replace the charceters with the comma - use the following regex:

var str = 'The quick brown fox jumps over the lazy dogs.'.replace(/.{3}/g, '$&,');
console.log(str);
Chayim Friedman
  • 14,050
  • 2
  • 21
  • 36
0

You can also use split() and join() operations for that output:

var str = "The quick brown fox jumps over the lazy dogs.";
var strArray = str.split('');
for(var i=1; i<=strArray.length; i++){
  if(i%3 === 0){
    strArray[i] = '*' + strArray[i];
  }
}
str = strArray.join('').replace(/\*/g,',');
console.log(str);
Ankit Agarwal
  • 29,658
  • 5
  • 35
  • 59
0

Try this:

var text = "The quick brown fox jumps over the lazy dogs.";

function addComma(text){
 let chunks = [];
 for(let i = 0; i < text.length; i+=3){
   chunks.push(text.substr(i,3));
 }
 return chunks.join();
}
console.log(addComma(text));
Damian Peralta
  • 1,786
  • 6
  • 11