My code is:
var result2 = result.replace(/[\W_]/g,"").replace(",","").replace(".","");
The code works i get what i need done, but I don't understand how the regular expression /[\W_]/g
works, and I can't find any documentation that i understand.
Regular expression is not a library nor is it a programming language. Instead, regular expression is a sequence of characters that specifies a search pattern in any given text (string). A text can consist of pretty much anything from letters to numbers, space characters to special characters.
It is a regular expression. That pattern replaces all whitespace characters \s+ by an empty string depending on that is is at the beginning of string ^\s+ or | at the end of the string \s+$ . g is for global modifier, what doesn't return after first match.
The RegExp \W Metacharacter in JavaScript is used to find the non word character i.e. characters which are not from a to z, A to Z, 0 to 9. It is same as [^a-zA-Z0-9].
A regular expression (sometimes called a rational expression) is a sequence of characters that define a search pattern, mainly for use in pattern matching with strings, or string matching, i.e. “find and replace”-like operations.
/
... /g
It's a global regex. So it'll operate on multiple matches in the string.[
... ]
This creates a character set. Basically it'll match any single character within the listed set of characters.\W_
This matches the inverse of "word characters" and underscores. Any non-word character.
Then you have a few one off replacements for comma and period. Honestly, if that's the complete code, /[\W_,.]/g
, omitting the two other replaces, would work just as well.
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