replace all occurrences of a string in JavaScript using regular expression

A regular expression is a pattern of characters. that is used to do pattern-matching "search-and-replace" from string

Using a regular expression find sub string from main string and replace all occurrences using regular expression.

oldString = "some test is here";
find = 'is';
replace = 'are';
oldString.replace(new RegExp((find.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')), 'g'), replace);

Alternate way:

str = 'abc xyx def abc'
find = 'abc';
re = new RegExp(find, 'g');
str.replace(re, '');

Tags:

Share:

Related posts