Replace commas with JavaScript Regex?


Let’s say the following are our strings with commas −

"My Favorite subject is,"
"My Favorite subject is, and teacher name is Adam Smith"
"My Favorite subject is, and got the marks 89"

To replace commas, use replace and in that, use Regular Expression. Following is the code −

Example

const makingRegularExpression = /,(?=[^,]*$)/;
replaceComma("My Favorite subject is,");
replaceComma("My Favorite subject is, and teacher name is Adam Smith");
replaceComma("My Favorite subject is, and got the marks 89");
function replaceComma(values){
   console.log(values, " ==== replaced by JavaScript ==== ", values.replace(ma
   kingRegularExpression, " JavaScript"));
}

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo164.js.

Output

This will produce the following output −

PS C:\Users\Amit\javascript-code> node demo164.js
My Favorite subject is, ==== replaced by JavaScript ==== My Favorite sub
ject is JavaScript
My Favorite subject is, and teacher name is Adam Smith ==== replaced by
JavaScript ==== My Favorite subject is JavaScript and teacher name is Ad
am Smith
My Favorite subject is, and got the marks 89 ==== replaced by JavaScript
==== My Favorite subject is JavaScript and got the marks 89

Updated on: 12-Sep-2020

551 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements