Languages

JavaScript - what is \W regex / '\w' and '\W' difference ?

3 points
Asked by:
Frida-Timms
667

What is \W (/\W/) regex and what is the difference between \w and \W?

1 answer
3 points
Answered by:
Frida-Timms
667

\w/\w/ - matches any word character (shortcut for [a-zA-Z_0-9]).

\W - /\W/ - matches any character that is not a word character (shortcut for [^\w]).

 

Practical example that shows how to extract \w and \W characters from any string:

// ONLINE-RUNNER:browser;

const text = 'abc-123?';

const result1 = text.match(/\w/g);
const result2 = text.match(/\W/g);

if (result1) {
	console.log(result1);  // ['a', 'b', 'c', 1, 2, 3]
}

if (result2) {
	console.log(result2);  // ['-', '?']
}

 

0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join