How to replace in Javascript, when replacement string is a variable

How to replace in Javascript, when replacement string is a variable

Very often we use replace method in javascript while replacing a string literal by another string literal.
But what if we need to replace a string whose value is held in a variable.

Here is the solution…

You can use a regular expression (often referred to as a RegEx or a RegExp). Regular expressions are much more powerful than standard string matching as they can use very complicated logic

// Let's take a look at the above example using regular expressions.
strReplaceSimple = strText.replace( new RegExp( "th", "" ), "[X]" );

alert( strReplaceSimple );

As you can see, we have the same replace happening. So let’s take a look at what’s going on. Instead of passing simple target string to the replace() method, we are passing in a regular expression (new RegExp()) object instance. The RegExp() takes two arguments, the expression and the search flags (left blank in our example). There are two universally valid flags: [g] which means globally replace and [i] which
means case INsensitive. By default, the regular expression is NOT global and case sensitive.

// So let's try to do a global replace using regular expressions.
strReplaceAll = strText.replace( new RegExp( "th", "g" ), "[X]" );

alert( strReplaceAll );

We just did a global replace in ONE line of code.

strReplaceAll = strText.replace( new RegExp( "th", "gi" ), "[X]" );

alert( strReplaceAll );

We just replaced out that additional “Th” simply by adding the flag [i] into the regular expression. That’s how powerful regular expressions are. But there’s more. Regular expressions are more than just flags. Much more!

Image that for some reason, you knew about regular expressions, but you didn’t know about the case insensitive flag [i]. You could have performed the same replace using this:

strReplaceAll = strText.replace( new RegExp( "(T|t)(H|h)", "g" ), "[X]" );

alert( strReplaceAll );

This groups the two letters together, and for each letter it tells the replacing algorithm to match t OR T followed by h OR H. There is sooo much more that regular expressions can do. Unfortunately, that is outside the scope of this entry. You should really look into regular expression both in Javascript and in ColdFusion / Java. They are amazing.

But what happens if you don’t want to do a simple replace? The replace method allows some very interesting flexibility. Up until now, we have been passing a simple string in a the “replace-in” argument ([X]). But, you don’t have to. You can pass in a function pointer instead.

For this example, let’s replace out the target string with a random letter in the brackets, not necessarily the X. First we have to create a function that will return the resultant random string

function RandomString(){
// Create an array of letters.
var arrLetters = ["A","B","C","D","E","V","W","X","Y","Z"];

// Use the random() method and the modulus (%) operator to
// pick a random letter from the above array.
var intLetter = (Math.floor( Math.random() * 10 ) % 9);

// Return the random letter string we get from the
// array of letters above.
return( "[" + arrLetters[ intLetter ] + "]" );
}

Try calling the function on its own a few times, just to see how it behaves.

alert(
RandomString() + "n" + RandomString() + "n" +
RandomString() + "n" + RandomString() + "n" +
RandomString() + "n" + RandomString() + "n" +
RandomString() + "n" + RandomString() + "n"
);

As you can see, it randomly (as random as possible) picks a letter to return. Now, let’s call the replace with the RandomString() method sent as the second argument. We will do this a few times so you can see the randomness in effect.

alert( strText.replace( "th", RandomString ) );
alert( strText.replace( "th", RandomString ) );
alert( strText.replace( "th", RandomString ) );

Notice that we are passing in a POINTER to the function but not actually calling it. RandomString vs. RandomString(). There’s one thing I did not mention yet. Not only can you pass in a function as an argument, but when the replace method is taking place, it passes in the target match as an argument to this function. We could have re-written the function as such:

function RandomString2( strTargetInstance) // This is the target string match instance.
{
var arrLetters = ["A","B","C","D","E","V","W","X","Y","Z"];
var intLetter = (Math.floor( Math.random() * 10 ) % 9);

// Return the random letter string we get from the
// array of letters above. This time, though, we are
// going to include the target string to demonstrate
// that it has been passed in.
return( "[" + strTargetInstance + " : " + arrLetters[ intLetter ] + "]" );
}

Now, we will run it again, just once, so you can see it in action.

alert( strText.replace( "th", RandomString2 ) );

Want to read more on this? do VISIT HERE

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.