Skip to content

How to get word, number, whitespace using Javascript regex

How to get word, number, whitespace using Javascript regex

In this post we will see some example of regular expression using which we will find words, non-words, numbers, non-numbers, whitespaces and non-whitespace characters. We will use special characters from regular expression Character classes. These special characters start with the ‘\’ backward slash. There are many more than the ones that I have displayed.


Words(alphanumeric)

We will start with getting words(alphanumeric characters including ‘_’) using regular expression. Here we use small ‘w’.

const wordRegex = /\w/g;
const str = 'hello123_-?!';

str.match( wordRegex ); // Output ['h', 'e', 'l', 'l', 'o', '1', '2', '3', '_']

Non-Words(alphanumeric)

Non-words(non-alphanumeric characters excluding ‘_’) using regular expression. We will use capital ‘W’.

const nonWordRegex = /\W/g;
const str = 'hello123_-?!';

str.match( nonWordRegex ); // Output ['-', '?', '!']

Number

Get numbers using regular expression. Here we use small ‘d’.

const numberRegex = /\d/g;
const str = 'hello123_-?!';

str.match( numberRegex ); // Output ['1', '2', '3']

Non-Number

Get non-numbers using regular expression. Here we us capital ‘D’.

const nonNumberRegex = /\D/g;
const str = 'hello123_-?!';

str.match( nonNumberRegex ); // Output ['h', 'e', 'l', 'l', 'o', '_', '-', '?', '!']

Whitespace

Get whitespace characters using regular expression. Here we use small ‘s’.

const whiteSpaceRegex = /\s/g;
const str = 'foo bar';

str.match( whiteSpaceRegex ); // Output [' ']

Non-Whitespace

Get non-whitespace characters using regular expression. Here we use capital ‘S’.

const whiteSpaceRegex = /\s/g;
const str = 'foo bar';

str.match( whiteSpaceRegex ); // Output ['f', 'o', 'o', 'b', 'a', 'r']

Conclusion

Hope this helps on how using regular expression we can find words, non-words, numbers, non-numbers, whitespaces and non-whitespace characters. See you in my next post. Till then enjoy coding 🙂

Further reading

Javascript Regex

How to to validate phone format using regex

Please share