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';
this will remove all the special character
this is really helpful and solve my issue. Please run the below code and ensure it works
Remove/Replace all special chars in Jquery :
If str = My name is "Ghanshyam" and from "java" background
and want to remove all special chars (") then use it
str=str.replace(/"/g,' ')
result: My name is Ghanshyam and from java background
Where g means Global @Thanks
replace(/[^a-z0-9\s]/gi, '')
will filter the string down to just alphanumeric values andreplace(/[_\s]/g, '-')
will replace underscores and spaces with hyphens:Source for Regex: RegEx for Javascript to allow only alphanumeric
Here is a demo: http://jsfiddle.net/vNfrk/
Since I can't comment on Jasper's answer, I'd like to point out a small bug in his solution:
The problem is that first code removes all the hyphens and then tries to replace them :) You should reverse the replace calls and also add hyphen to second replace regex. Like this:
Assuming by "special" you mean non-word characters, then that is pretty easy.
Remove numbers, underscore, white-spaces and special characters from the string sentence.
Demo