JavaScript

Javascript String Replace Example

Ever wrote an entire post about the simmilarities between two programming languages, and realized at the end of your 1000 word essay that “simmilarities” is actually written as “similarities”?

Now you’d have to change that, and it’s horrible because you actually used that word like a dozen times! I would know that, as the engineering student who learned how to spell “engineer” halfway through her second year of university.

So now I want to tell you how to fix this using Javascript.
 
 

Replacing one string

Javascript has a ready made function to do the replacing of a string or a part of it with another string. You use it like below:

var text="Three important Swiss customs for tourists to know" +
    " deal with religion, greeting, and punctuality";

console.log(text.replace("Swiss" , "Dutch"));

As you see, you just have to use the function replace() where the first argument is the string we want to replace, and the second one is the new string we want instead. We have used the console.log() function to make the result more visible by having the console put out the result. The arguments can be put in as many different forms as you can express a string.

Still, if you use this code snippet for a text that contains the string you want to be replaced multiple times, you will see the effect only on the first occurrence. So, how about when you want to replace all the strings in the paragraph or even in the whole book?! You call the good ol’ loops!

Replacing all the strings

When you’ve repeated a mistake all over a text, or even just want to make sure you haven’t, you would have to find a new way to do that, as there is no replaceAll() function in Javascript. And we’ll do exactly what is done in these cases: we’ll make one ourselves.

Now, if you’re only running the loop one one particular string you can do that quite easily, but as you’re going to work with indexes, in case you’re using it very often, you might want to create a replaceAll() function as a prototype into the Javascript String object, so that it can apply to all of them.

The function would look like this:

String.prototype.replaceAll = function(strTarget,  strSubString ){
    var text = this ;
    var intIndexOfMatch = text.indexOf( strTarget );

    while (intIndexOfMatch != -1){
        text = text.replace( strTarget, strSubString );

        intIndexOfMatch = text.indexOf( strTarget );
    }

    return( text );
};

Our custom function will take two arguments: the string we want to replace, the which we have named strTarget and the string we want to replace in named strSubString. Whenever the index of the match is different than -1, which means that a matching substring is found, we make the replacement and perform the check again, until there is no match found. The function will then return the text with all the replacements. We use it just like a replace() function, and just in case you forgot already, look below:

replacedText = text.replaceAll( "Four", "Three" );

console.log( replacedText );

Notice that these functions, both replace() and replaceAll() are case sensitive, and while it will replace every instance where a specific string is found, the other strings with different case sensivity will be ignored. To make the functions case insensitive we will have to do a couple of changes.

Case insensitive replacement

Case insensitive replacement is done in two ways: using an operator in the argument that is to be replaced, or using regular expressions.

Using regular expressions

We can do the replacement by passing a regular expression object instance, or RegEx (a.k.a RegExp), which takes two arguments: the expression and the search flags. Two of the most used, and valid everywhere flags are [g] and [i], respectively globally replace and case insensitive. You would use them like this:

strReplaceAll = text.replace( new RegExp( "three", "gi" ), "four" );

console.log( strReplaceAll );

The replacement we’re making is both conducted globally and is case insensitive.

Using operators

If it happens that you forget the flags, you can do it using operators instead. The code would go like this:

strReplaceAll = text.replace( new RegExp( "(T|t)(H|h)", "g" ), "t" );

console.log( strReplaceAll );

You see that instead of the flag [i], we have used the operator “or”, which means that the method will search for T or t and H or h.

This simply you can replace strings or parts of it with other ones.

Download the source code

This was an example of string replacement using Javascript.

Download
You can download the full source code of this example here: StringReplace

Era Balliu

Era is a Telecommunications Engineering student, with a great passion for new technologies. Up until now she has been coding with HTML/CSS, Bootstrap and other front-end coding languages and frameworks, and her recent love is Angular JS.
Subscribe
Notify of
guest

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

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button