Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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';
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
209 views
Welcome To Ask or Share your Answers For Others

1 Answer

replace(/[^a-z0-9s]/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-9s]/gi, '').replace(/[_s]/g, '-')

Source for Regex: RegEx for Javascript to allow only alphanumeric

Here is a demo: http://jsfiddle.net/vNfrk/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...