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
  • 772
  • 5
  • 17
  • 32

3 Answers3

2

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
  • 47,971
  • 5
  • 48
  • 77
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
  • 30,378
  • 5
  • 37
  • 62
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,846
  • 7
  • 11