Reputation: 1892
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
Upvotes: 53
Views: 355711
Reputation: 1
Excluding special characters: /^[^@~`!@#$%^&()_=+\\';:"\/?>.<,-]$/ this regular expression helps to exclude special characters from the input.
Exclude special characters and emojis : /^([^\u2700-\u27BF\uE000-\uF8FF\uDD10-\uDDFF\u2011-\u26FF\uDC00-\uDFFF\uDC00-\uDFFF\u005D\u007C@~`!@#$%^&()_=+[{}"\\';:"\/?>.<,-\s])$/ this is a regular expression to exclude both special characters and emojis from the input. Given are the Unicode ranges of the emojis , mathematical symbols and symbols in other languages.
Upvotes: 0
Reputation: 10907
to remove symbol use tag [ ]
step:1
[]
step 2:place what symbol u want to remove eg:@ like [@]
[@]
step 3:
var name = name.replace(/[@]/g, "");
thats it
var name="ggggggg@fffff"
var result = name.replace(/[@]/g, "");
console .log(result)
Extra Tips
To remove space (give one space into square bracket like []=>[ ])
[@ ]
It Remove Everything (using except)
[^place u dont want to remove]
eg:i remove everyting except alphabet (small and caps)
[^a-zA-Z ]
var name="ggggg33333@#$%^&**I(((**gg@fffff"
var result = name.replace(/[^a-zA-Z]/g, "");
console .log(result)
Upvotes: 9
Reputation: 517
This should work as well
text = 'the car? was big and* red!'
newtext = re.sub( '[^a-z0-9]', ' ', text)
print(newtext)
the car was big and red
Upvotes: 1
Reputation: 71538
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, "");
Upvotes: 83
Reputation: 60224
If you don't mind including the underscore as an allowed character, you could try simply:
result = subject.replace(/\W+/g, "");
If the underscore must be excluded also, then
result = subject.replace(/[^A-Z0-9]+/ig, "");
(Note the case insensitive flag)
Upvotes: 16
Reputation: 594
To remove the special characters, try
var name = name.replace(/[!@#$%^&*]/g, "");
Upvotes: 22