I have a string like this:
var str = "I'm a very^ we!rd* Str!ng.";
What I would like to do is removing all special characters from the above string and replace spaces and in case they are being typed, underscores, with a - character.
The above string would look like this after the "transformation":
var str = 'im-a-very-werd-strng';
Remove Special Characters in JavaScript With jQuery "; var stringValue = $("#stringValue"). text(); for (var i = 0; i < specialChars. length; i++) { stringValue = stringValue. replace(new RegExp("\\" + specialChars[i], "g"), ""); } $('#demo').
Use the replace() method to remove all special characters from a string, e.g. str. replace(/[^a-zA-Z0-9 ]/g, ''); . The replace method will return a new string that doesn't contain any special characters.
createTextNode(), which replaces special characters with their HTML entity equivalents (such as < for <).
replace(/[^a-z0-9\s]/gi, '')
will filter the string down to just alphanumeric values and replace(/[_\s]/g, '-')
will replace underscores and spaces with hyphens:
str.replace(/[^a-z0-9\s]/gi, '').replace(/[_\s]/g, '-')
Source for Regex: RegEx for Javascript to allow only alphanumeric
Here is a demo: http://jsfiddle.net/vNfrk/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With