How to replace all occurrences of a sub-string in a string with JavaScript


If you need to replace all the occurrences of a sub-string in a string in your JavaScript code, you have to call the built-in function replace() with a regular expression.
More info about the built-in function replace().

Here is a simple function that does that.

/**
 * Replaces all occurrences of "search" in "subject" with "replace".
 * @param {String} search The value being searched for, otherwise known as the needle.
 * @param {String} replace The replacement value that replaces found search values.
 * @param {String} subject The string being searched and replaced on, otherwise known as the haystack.
 */
function replaceAll(search, replace, subject) {
	return subject.replace(new RegExp(search, 'g'), replace);
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s