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:
    These icons link to social bookmarking sites where readers can share and discover new web pages.

    • Digg
    • Furl
    • del.icio.us
    • StumbleUpon
    • MisterWong
    • DZone
    • Technorati

    Tags: , , ,

Leave a Reply