Edupala

Comprehensive Full Stack Development Tutorial: Learn Ionic, Angular, React, React Native, and Node.js with JavaScript

Javascript String replace using replace() Method

Javascript String replace

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 the first occurrence of a character

var str = “hello,,”;
str = str.replace(‘,’, “|”);
alert(str);
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, “|”);
alert(myStr);
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’);
alert(str);
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
<html>
<head>
 <script>
   function detectBrowser() {
     let str = "object_realtime_tr~ading3$"
     str = str.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g, '_');
     document.getElementById("replaceString").innerHTML = str;
   }
 </script>
</head>

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

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

</html>

Related posts

Javascript String replace using replace() Method

Leave a Reply

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

Scroll to top