Replacing text with Javascript

Posted in Javascript -

Javascript has the .replace method for strings which allows for replacement of strings within strings using regular expressions. This post has some examples of replacing text with Javascript.

If, for example, you had the following variable:

var foo = "this is a test string that we'll do some string replacements on";

you could replace "this is a test" with "this is a modified" by doing this:

var bar = foo.replace(/this is a test/, 'this is a modified');

and the resulting string would be:

this is a modified string that we'll do some string replacements on

The first parameter to replace() is a regular expression. The text that is to be replaced must be bounded by / and must not be in quotes.

The following example is wrong because it has quotes around it:

foo.replace('/this is a test/', 'this is a modified');

Because it's a regular expression you can do some clever stuff such as putting a ^ at the start to match from the start of the string, $ at the end to match at the end of the string and e.g. [a-e] to match a range of letters, in this example from a to e.

Another example, changing just the first instance of "this" to "that" would look like this:

var foo = "this this this this";
var bar = foo.replace(/^this/, 'that');

The variable bar would now contain:

that this this this

If you wanted to replace some HTML text within an element using jQuery, for example, you could use jQuery's .html() function get and set the HTML.

Here's some example HTML:

<p id="something">this is a test string that we'll do some string replacements on</p>

And here's the jQuery function which would transform it:

$("#something").html($("#something").html().replace(/this is a test/, 'this is a modified'));

Related posts: