To remove special characters from a string in JavaScript, you can use the `replace` method with a regular expression pattern.
In this example,
str1
with a value of "Hello! World!"
.replace
method with a regular expression pattern /[^a-zA-Z0-9 ]/g
to replace all non-alphanumeric characters and spaces with an empty string.str1
to the console.let str1 = "Hello! World!";
str1 = str1.replace(/[^a-zA-Z0-9 ]/g, '');
console.log('Modified string:', str1);
Modified string: Hello World
In this example,
str2
with a value of "apple@banana"
.replace
method with a regular expression pattern /[^a-zA-Z0-9 ]/g
to replace all non-alphanumeric characters and spaces with an empty string.str2
to the console.let str2 = "apple@banana";
str2 = str2.replace(/[^a-zA-Z0-9 ]/g, '');
console.log('Modified string:', str2);
Modified string: applebanana
In this tutorial, we learned How to Remove Special Characters from a String in JavaScript language with well detailed examples.