Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to interpret this regular expression /[\W_]/g

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.

like image 733
Jarod Bassett Avatar asked Feb 10 '16 19:02

Jarod Bassett


People also ask

How do you read a regular expression?

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.

What is s +|\ s +$/ g?

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.

What is the use of W in regex?

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].

How do you describe a regular expression?

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.


1 Answers

/ ... /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.

like image 149
Joseph Marikle Avatar answered Nov 01 '22 11:11

Joseph Marikle