Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery remove special characters from string and more

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'; 
like image 683
Roel Avatar asked Jan 23 '12 22:01

Roel


People also ask

How to remove special characters from a string using JQuery?

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').

How to remove special characters from string JavaScript?

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.

How to remove html special characters in JavaScript?

createTextNode(), which replaces special characters with their HTML entity equivalents (such as &lt; for <).


1 Answers

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/

like image 156
Jasper Avatar answered Oct 10 '22 03:10

Jasper