# \w vs \W in JavaScript regex?

Front End TechnologyJavascriptObject Oriented Programming

## \w vs \W

There is a lot of variation between '\w' and '\W' in javascript in which the former looks after 'word characters' such as alpha-numerics whereas the latter looks after 'non-word characters' such as &, ^, %, etc. Let's discuss it in a nutshell.

### syntax-1

new RegExp("\\w", "g");

The above code gives out the syntax to find the 'word characters' in javascript.

### syntax-2

new RegExp("\\W", "g");

The above code gives out the syntax to find the 'non-word characters' in javascript.

### Example-1

In the following example, \w along with global object 'g' is used. If global object 'g' is not used then, only the first alphanumeric letter, if present, will be displayed in the output. Since here global object 'g' is used, all the alpha-numeric characters are displayed as shown in the output.

Live Demo

<html>
<body>
<script>
var str = "**Tutorix is the best e-learning platform%!";
var regpat = /\w/g;
var result = str.match(regpat);
document.write(result);
</script>
</body>
</html>

### Output

T,u,t,o,r,i,x,i,s,t,h,e,b,e,s,t,e,l,e,a,r,n,i,n,g,p,l,a,t,f,o,r,m

### Example-2

In the following example, '\W' is used therefore the 'non-word characters' are displayed in the output. If the global object 'g' is not used then only the first "non-word character" will be displayed. Since here "g" is used all the non-word characters are displayed as shown in the output.

Live Demo

<html>
<body>
<script>
var str = "**Tutorix is the best e-learning platform%!";
var regpat = /\W/g;
var result = str.match(regpat);
document.write(result);
</script>
</body>
</html>

### Output

*,*, , , , ,-, ,%,!
Published on 26-Aug-2019 13:08:18