Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex remove all special characters except numbers?

I would like to remove all special characters (except for numbers) from a string. I have been able to get this far

var name = name.replace(/[^a-zA-Z ]/, ""); 

but it seems that it is removing the first number and leaving all of the others.

For example:

name = "collection1234"; //=> collection234 

or

name = "1234567"; //=> 234567 
like image 479
EHerman Avatar asked Dec 22 '13 17:12

EHerman


People also ask

How do I remove all characters from a string except numbers?

To remove all characters except numbers in javascript, call the replace() method, passing it a regular expression that matches all non-number characters and replace them with an empty string. The replace method returns a new string with some or all of the matches replaced.

Which regexp pattern and function can be used to replace special characters and numbers in a string?

If you are having a string with special characters and want's to remove/replace them then you can use regex for that. Use this code: Regex. Replace(your String, @"[^0-9a-zA-Z]+", "")

What does \+ mean in regex?

Example: "a\+" matches "a+" and not a series of one or "a"s. ^ the caret is the anchor for the start of the string, or the negation symbol. Example: "^a" matches "a" at the start of the string. Example: "[^0-9]" matches any non digit.


2 Answers

Use the global flag:

var name = name.replace(/[^a-zA-Z ]/g, "");                                     ^ 

If you don't want to remove numbers, add it to the class:

var name = name.replace(/[^a-zA-Z0-9 ]/g, ""); 
like image 131
Jerry Avatar answered Sep 23 '22 23:09

Jerry


To remove the special characters, try

var name = name.replace(/[!@#$%^&*]/g, ""); 
like image 35
T-Dor Avatar answered Sep 20 '22 23:09

T-Dor