Problem:
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,. ]/);
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>