Objects in this mirror are closer to Microsoft Technologies. DNM objective is to help users on Microsoft technologies by providing Articles, snippets, Interview Questions.

31 August 2012

Remove special characters (!@#$%.etc) with empty string from a string using JavaScript


Using java script if you want to remove special characters from a string, we can achieve using regular expression.

The below code will allow alphabets (lower and upper case) and numbers in a string.
var str = '@This is sample sting from <.NET Mirror> Ready! 1#2%3*Go';
var rStr = str.replace(/[^a-zA-Z0-9]+/g, '');
alert(rStr);
Output : ThisissamplestingfromNETMirrorReady123Go

If you want allow some of special characters then add them to expression. In the below code we will try to add space and dot.  so now the expression allows alphabets, numbers space and dot.

var rStr1 = str.replace(/[^a-zA-Z0-9 .]+/g, '');
alert(rStr1);
Output: This is sample sting from .NET Mirror Ready 123Go

0 Comments:

Post a Comment