How can I perform a str_replace in JavaScript, replacing text in JavaScript?

Vish picture Vish · Apr 2, 2011 · Viewed 216.1k times · Source

I want to use str_replace or its similar alternative to replace some text in JavaScript.

var text = "this is some sample text that i want to replace";
var new_text = replace_in_javascript("want", "dont want", text);
document.write("new_text");

should give

this is some sample text that i dont want to replace

If you are going to regex, what are the performance implications in comparison to the built in replacement methods.

Answer

sdleihssirhc picture sdleihssirhc · Apr 2, 2011

You would use the replace method:

text = text.replace('old', 'new');

The first argument is what you're looking for, obviously. It can also accept regular expressions.

Just remember that it does not change the original string. It only returns the new value.