Replacing text with Javascript
Posted February 10th, 2009 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:
- Trimming strings with Javascript (Tuesday, June 16th 2009)
- Multi line strings with Javascript (Tuesday, May 26th 2009)
- Pad a number to two digits with Javascript (Tuesday, April 21st 2009)
- Pad a number with leading zeroes in Javascript (Sunday, April 19th 2009)
- Loading content with jQuery AJAX (Wednesday, January 14th 2009)
- Find the index of a string within a string with Javascript (Friday, November 28th 2008)
Share or Bookmark
Share or Bookmark this page using the following services. You will need to have an account with the selected service in order to post links or bookmark this page.
Subscribe or Follow
Subscribe via RSS or email, or follow me on Facebook or Twitter below. The RSS icon takes you through to Feedburner where you can select the service or application to use.

