Skip to content

JavaScript replaces special characters | Example code

  • by

Use replace() function with a regular expression to replace special characters in Python.

string.replace(searchVal, newvalue)

Example replaces special characters in JavaScript

A simple example code removes special characters from a string and replaces them with the _ character (underscore).

Replace those characters: & / \ # , + ( ) $ ~ % .. ' " : * ? < > { }

<!DOCTYPE html>
<html>

<body>

  <script>
    
    var string = "img_realtime_tr~ading3$";
    var text =  string.replace(/[^a-zA-Z0-9]/g,'_');  

    console.log(text)

  </script>

</body>
</html>

Output:

JavaScript replaces special characters

Another example

  <script>
    
    var values = '&677,431,444,98777';
    var result=values.replace(/(^\&)|,/g, '');
    console.log(result);

  </script>

Output: 67743144498777

Do comment if you have any doubts or suggestions on this JS replace char topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading