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