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?
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] .
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.
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, '');
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