Javascript algorithm problem

How can i strip all white spaces and special characters from a string in javascript?

If you only want letters and numbers left? If so, you can use a regular expression like:

var str = 'hello ;;; !!! _" " " goodbye';
var cleanStr = str.replace(/\W|_/g,'');
console.log(cleanStr); // 'hellogoodbye'
1 Like

Thank you.
But can you please explain that replace method working with that regular expression.
This will help me understand it a little better.

It replaces all non-word characters or the underscore character _ with a blank string. A word character is a character from a-z, A-Z, 0-9, including the _ (underscore) character. The \W stands for all non-word characters. The | means OR. The _ is just the underscore character which is necessary, because underscore characters are word characters in regex. The g tells the regex to perform a global match (find all matches rather than stopping after the first match).

1 Like