JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to replace comma with semicolon in JavaScript?

Use the string replace() method, to replace comma with semicolon, e.g. str.replace(/,/g, ';'). The replace() method will return a new string in which commas are replaced with semicolons.

let str = 'React,Angular,Vue,Bootstrap';
let newString = str.replace(/,/g, ';')
console.log(newString); //"React;Angular;Vue;Bootstrap"

The String.replace() method accepts two arguments:

  1. Regular expression or string: It is the pattern or string that you want to replace.
  2. Replacement string: The string will replace the matched pattern or string.

Here, we have passed a regular expression /,/g, and semicolon ';' as arguments to the replace() method.

Instead of a regular expression, if we have passed a comma as a string, then only the first occurrence of the comma is replaced with a semicolon.

let str = 'React,Angular,Vue,Bootstrap';
let newString = str.replace(',', ';')
console.log(newString); //"React;Angular,Vue,Bootstrap"

Always remember one thing, whenever you want to replace all the occurrences of commas, pass a regular expression with the g flag.

Recommended Posts