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
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.
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]+", "")
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.
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, "");
To remove the special characters, try
var name = name.replace(/[!@#$%^&*]/g, "");
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