How to remove non-word characters in JavaScript?

JavascriptObject Oriented ProgrammingFront End Technology

Removing non-word characters

To remove non-word characters we need to use regular expressions. The logic behind removing non-word characters is that just replace the non-word characters with nothing('').

Example

In the following example there are many non-word characters and in between them there exists a text named "Tutorix is the best e-learning platform". So using regular expressions the non-word characters were replaced with nothing('') so as to get the word characters as the output.

Live Demo

<html>
<body>
<script type="text/javascript">
   function remNonWord (string) {
      if ((string===null) || (string===''))
      return false;
      else
      string = string.toString();
      var PATTERN = /[^\x20\x2D0-9A-Z\x5Fa-z\xC0-\xD6\xD8-\xF6\xF8-\xFF]/g;
      return string.replace(PATTERN, '');
   }
   document.write(remNonWord('Tutorix is the ~!@^&";\'/?>#$%*()+`={}[]|\\:<.,best e-learning            platform'));
</script>
</body>
</html>

Output

Tutorix is the best e-learning platform
raja
Published on 24-Jun-2019 13:06:16
Advertisements