1

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.

2
  • 3
    .replace(/(.{3})/g,"$1,") - you forgot to put back what you captured. Or, .replace(/.{3}/g,"$&,") Commented Jul 17, 2018 at 14:42
  • Do you want the space to be counted? Commented Jul 17, 2018 at 14:45

3 Answers 3

2

Your problem is that you replace the characters with the comma rather than replacing the characters with themselves PLUS the comma - use the following regex:

var str = 'The quick brown fox jumps over the lazy dogs.'.replace(/.{3}/g, '$&,');
console.log(str);

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

Comments

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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.