Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all non alphanumeric and any white spaces in string using javascript

I'm trying to remove any non alphanumeric characters ANY white spaces from a string.

Currently I have a two step solution and would like to make it in to one.

var name_parsed = name.replace(/[^0-9a-zA-Z ]/g, ''); // Bacon, Juice | 234
name_parsed = name_parsed.replace(/ /g,'')
console.log(name_parsed); //BaconJuice234

Could someone let me know how to achieve above in one execution and not two?

like image 399
BaconJuice Avatar asked Jun 05 '14 14:06

BaconJuice


People also ask

How do you remove non-alphanumeric characters from a string?

A common solution to remove all non-alphanumeric characters from a String is with regular expressions. The idea is to use the regular expression [^A-Za-z0-9] to retain only alphanumeric characters in the string. You can also use [^\w] regular expression, which is equivalent to [^a-zA-Z_0-9] .

How do you delete an alphanumeric character?

We can remove non-alphanumeric characters from the string with preg_replace() function in PHP. The preg_replace() function is an inbuilt function in PHP which is used to perform a regular expression for search and replace the content.


1 Answers

Remove the space from the first set and will do the job:

name.replace(/[^0-9a-zA-Z]/g, '');

You may read this code as "remove all characters that are not digits ([0-9]) and alpha characters ([a-zA-Z])".

Alternatively, you can use the i flag to make your regular expression ignore case. Then the code can be simplified:

name.replace(/[^0-9a-z]/gi, ''); 
like image 161
VisioN Avatar answered Oct 12 '22 06:10

VisioN