Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript Regex for allowing alphanumeric Characters,comma, dots, spaces

In PHP, I used the following codes to Remove special characters except alphabets, numbers,comma, fullstop and space.

$text = "test, 22222 @% test test test.";
$message = preg_replace('/[^A-Za-z0-9,. ]/', '', $text);

How can I achieve the same using javascript. I knew of javascript replace params below but its not giving me what I want

var text = "test, 22222 @% test test test.";

var message = text.replace(/[^A-Za-z0-9,. ]/);

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

var text = "test, 22222 @% test test test.";
var message = text.replace(/[^A-Za-z0-9,. ]/g, '');
  • The key difference is that you need to add the g flag at the end of the regular expression to indicate global matching. This way, it will replace all occurrences of the specified characters in the input string.

  • So, in the code above, any character that is not a letter (A-Za-z), number (0-9), comma, period (full stop), or space will be removed from the text string, and the result will be stored in the message variable.

    function processText() {
      var originalText = document.getElementById("originalText").value;
      var processedText = originalText.replace(/[^A-Za-z0-9, .]/g, '');
      document.getElementById("resultText").textContent = processedText;
    }
    <p>Original Text:</p>
    <textarea id="originalText" rows="4" cols="50">test, 22222 @% test test test.</textarea>
    
    <button onclick="processText()">Process Text</button>
    
    <p>Processed Text:</p>
    <p id="resultText"></p>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

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

Continue reading