How to Replace all Occurrences of a String in JavaScript

JavaScript replace() method is used to replace a string with a specific value. The replace() method searches for a specified value in a string and returns a string with replaced value. Generally, JavaScript string replace() method replace only the first occurrence of a string.

JavaScript replace() function searches for the first occurrence of a string inside another string and replaces with the specified value. If you want to replace all the matching string from a string, Regular Expression (regex) need to be used. The combination of JavaScript replace() function and regular expression, is used to find and replace all occurrences of a string inside another string using JavaScript.

The following code snippets search and replace all CW with CodexWorld in the string using JavaScript replace() function with the regular expression.

var str = 'CW is the best blog, visit CW now.';

// Replace CW with CodexWorld
var res = str.replace(/\CW/g, 'CodexWorld');

The following code snippets search and replace all whitespace characters with an underscore (_) in the string using JavaScript replace() function with the regular expression.

var str = 'CW is the best blog, visit CW now.';

// Replace ' ' with _
var res = str.replace(/\ /g, '_');

Leave a reply

keyboard_double_arrow_up