Javascript String replace using replace() Method

The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a Regular Express, and the replacement can be a string or a function to be called for each match.

Javascript string replace example

We’ll demonstrate a few examples of the string replace() method.

Example 1: Replace first occurrence of character

var str = “hello,,”;
str = str.replace(‘,’, “|”);
Output: hello|,

Example 2: Replace all occurrences of character.
In the example below we will replace, comma with | pipe.

var myStr = “hello,,world”;
myStr = myStr.replace(/,/g, “|”);
Output: hello||world,

In the above example, we used the global (g) flag on the regular expression literal to match all occurrences. The i flag is also often useful for a case-insensitive match.

Example 3: Replace the last occurrence of a character.
In this case, we will be replacing the last, comma character with | pipe.

var str = ‘Hello,,world’;
str = str.replace(/,([^,]*)$/, ‘|’+’$1’);
Output: hello,|world,

Javascript replace special characters

In the next example, we want to replace a special character in a string with a character let says underscore using replace() method.

Javascript String replace
Javascript replace special characters
   function detectBrowser() {
     let str = "object_realtime_tr~ading3$"
     str = str.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g, '_');
     document.getElementById("replaceString").innerHTML = str;

    <h4>Javascript replace special character with underscore character</h4>
        Original string: <b>object_realtime_tr~ading3$</b>
    <p id="replaceString"></p>

    <button type="button" onclick="detectBrowser()">Convert string character</button>


Related posts

Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top