Replace commas with JavaScript Regex?

In JavaScript, you can replace commas in strings using the replace() method combined with regular expressions. This is particularly useful when you need to replace specific comma patterns, such as the last comma in a string.

Problem Statement

Consider these example 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"

We want to replace the last comma in each string with " JavaScript".

Using Regular Expression to Replace Last Comma

The regular expression /,(?=[^,]*$)/ matches a comma that is followed by any characters except commas until the end of the string, effectively targeting the last comma.

const makingRegularExpression = /,(?=[^,]*$)/;

function replaceComma(values) {
    console.log(values, " ==== replaced by JavaScript ==== ", values.replace(makingRegularExpression, " JavaScript"));
}

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");
My Favorite subject is, ==== replaced by JavaScript ==== My Favorite subject is JavaScript
My Favorite subject is, and teacher name is Adam Smith ==== replaced by JavaScript ==== My Favorite subject is JavaScript and teacher name is Adam Smith
My Favorite subject is, and got the marks 89 ==== replaced by JavaScript ==== My Favorite subject is JavaScript and got the marks 89

How the Regular Expression Works

  • , - Matches a comma character
  • (?=[^,]*$) - Positive lookahead that ensures the comma is followed by zero or more non-comma characters until the end of string
  • This pattern effectively finds the last comma in the string

Alternative Approaches

You can also replace all commas or use different patterns:

// Replace all commas
let text = "My, Favorite, subject, is,";
console.log("All commas:", text.replace(/,/g, " -"));

// Replace only the first comma
console.log("First comma:", text.replace(/,/, " -"));

// Replace commas followed by space
console.log("Comma + space:", text.replace(/, /g, " - "));
All commas: My - Favorite - subject - is -
First comma: My - Favorite, subject, is,
Comma + space: My -Favorite -subject -is,

Conclusion

Regular expressions provide powerful pattern matching for replacing commas in JavaScript strings. The /,(?=[^,]*$)/ pattern specifically targets the last comma, making it useful for text formatting tasks.

Updated on: 2026-03-15T23:18:59+05:30

750 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements