Javascript Strings: How to Do String Replacement in JS

This morning I set about making a simple script to clean extra newline characters out of text. I could easily have processed the form contents in PHP, but I wanted to use Javascript to avoid reloading the page.

The concept seemed simple enough, but I ran into a problem – I didn’t know how to do string replacement in Javascript. The first thing I thought was, “What is the Javascript equivalent to str_replace?”

The JS str_replace – String.replace()

As it turns out, the closest thing in Javascript to str_replace is the replace method of the String class. It’s actually more akin to preg_replace – since it uses regular expressions – but it’s the closest thing I could find for a built-in string replacement function.

It’s implementation is pretty simple. Create a new string object. Then call the replace method with two parameters – a regular expression to match and a string to replace it with.

var hello = new String('Hello World!');
var goodbye = hello.replace(/hello/i, 'Goodbye');

In this example, we do a simple search for the word ‘hello’ (the ‘i’ signifies that the search is case insensitive). When we find ‘hello,’ we replace it with goodbye.

Using Variable Values Inside Regex

That’s simple enough. However, what if you don’t want to hard-code the regular expression?

I was left wondering how I could use a variables value within the regular expression for the search. If I placed the variable inside the / / boundaries of the regex, it would simply search for the name of the variable.

I eventually stumbled across the RegExp class – which incidentally makes it easier to build a regex expression. You create an instance of the RegExp class by passing it two parameters – the string to match and any modifiers (‘i’ or ‘g’) that should be used for the search.

var hello = new String('Hello World!');
var matchWord = new String('hello');
var match = new RegExp(matchWord, 'i');
 
var goodbye = hello.replace(match, 'Goodbye');

This has the same effect as the last example – except now the string to match comes from the variable matchWord. With this, you could use some type of user input to determine what to match and replace.

Recap – Replacing Strings in Javascript

To recap…

  • There is no direct equivalent to str_replace in Javascript.
  • Use String.replace – which is very similar to preg_replace.
  • Two parameters – a regex to match and a string to replace it with.
  • Build an instance of the RegExp class to use variable values in your regex.
  • Bookmark and Share:
    • Digg
    • Furl
    • del.icio.us
    • StumbleUpon
    • MisterWong
    • DZone
    • Technorati

    Tags: , , ,

2 Comments to “Javascript Strings: How to Do String Replacement in JS”

  1. How to do String Replacement in Javascript - Tutorial Collection said this on

    [...] View Tutorial No Comment var addthis_pub=”izwan00″; BOOKMARK This entry was posted on Monday, June 8th, 2009 at 2:19 am and is filed under Javascript Tutorials. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site. [...]

  2. Liza Kintigh said this on

    Greetings. I genuinely did some network surfing and found this blog . I determined by means of this blog put up and it is. Genuinely unbelievable. I decidedly genuinely enjoy your web site . Absolutely , the chunk of sending is in guarantee the.Very finest on this genuinely deserving though subject. I added it and i ‘m hunting ahead to your upcoming site .reports. I besides observed that your web site has some first class colligating filled out to it. I will correct apart get.Hold of your rss feed to rest informed of any revisions . Howling information you got right here. Delight. Keep revise on your fantastic article. Thanks.I was analyzing something else about this on another web log. Interesting. Your position on it is diametrically. Defended to what I read originally. I am stock still reflecting over the various points of view, but I ‘m prepared to a. Keen extent toward yours. And regardless, that’s what is therefore topnotch about modernized democracy and the mart .of thoughts on line . I will are available back once more .

Leave a Reply