How to Remove Special Characters in JavaScript
- Remove Special Characters in JavaScript Without jQuery
- Remove Special Characters in JavaScript With jQuery
Sometimes, we have special characters in our string that we don’t want to display. We use the replace()
method that searches for a regular expression (also called regex) or a value.
It outputs a new string with the replaced value but does not change the original string. Let’s start with the basic one.
Remove Special Characters in JavaScript Without jQuery
JavaScript Code:
javascriptCopyvar stringValue = '&485,431,0458,92347';
var newString = stringValue.replace(/(^\&)|,/g, ' ');
console.log('String before replacement: ' + stringValue);
console.log('String after replacement: ' + newString);
Output:
textCopy"String before replacement: &485,431,0458,92347"
"String after replacement: 485 431 0458 92347"
In the above code, (^\&)
removes the &
symbol and ,
(comma) for removing ,
from the string. The g
modifier says global, and |
is used as OR
operator.
It means the replace()
function takes a regular expression that removes &
and ,
from the whole string and replaces it with a single white space.
We can also define a string that contains all special characters and use that string in the RegExp()
object to make the code more readable and maintainable. See the following code.
javascriptCopyvar specialChars = '!@#$^&%*()+=-[]\/{}|:<>?,.';
var stringValue = '&485,431,(0458,]92347:';
console.log('String before replacement: ' + stringValue);
for (var i = 0; i < specialChars.length; i++) {
stringValue =
stringValue.replace(new RegExp('\\' + specialChars[i], 'g'), '');
}
console.log('String after replacement: ' + stringValue);
Output:
textCopy"String before replacement: &485,431,(0458,]92347:"
"String after replacement: 485431045892347"
We iterate over a complete string to search for each special character and remove it to get the above output. Here, the RegExp
object matches the text within the pattern.
You can find more about it here.
Suppose we get a string from the HTML element, replace special characters, and display it back on your screen. Let’s practice that with jQuery.
Remove Special Characters in JavaScript With jQuery
HTML Code:
htmlCopy<!DOCTYPE html>
<html>
<head>
<title> Remove Special Characters</title>
</head>
<body>
<h2>The Original String</h2>
<p id="stringValue">Do [a search-for special characters] in string &:search and, "remove"#@ them:</p>
<h2>String After Replacement</h2>
<p id="demo"></p>
</body>
</html>
JavaScript Code:
javascriptCopyvar specialChars = '!@#$^&%*()+=-[]\/{}|:<>?",.';
var stringValue = $('#stringValue').text();
for (var i = 0; i < specialChars.length; i++) {
stringValue =
stringValue.replace(new RegExp('\\' + specialChars[i], 'g'), '');
}
$('#demo').text(
stringValue) // text() returns the text content of the selected element.
Output: