Sometimes, we want to use a regex to add a space after each comma in JavaScript.
In this article, we’ll look at how to use a regex to add a space after each comma in JavaScript.
How to use a regex to add a space after each comma in JavaScript?
To use a regex to add a space after each comma in JavaScript, we can use the string replace
method.
For instance, we write:
const input = '1,2,3,4,5'
const output = input.replace(/(d+,)/g, '$1 ');
console.log(output)
to call input.replace
with a regex that matches all instances of digits with a comma after it.
Then we replace matches with a extra space with '$1 '
.
Therefore, output
is '1, 2, 3, 4, 5'
.
Conclusion
To use a regex to add a space after each comma in JavaScript, we can use the string replace
method.