DEV Community

loading...

Javascript regex part 5 quick advanced shortcuts

scdan0624 profile image SCDan0624 ・1 min read

Intro

In previous blogs we looked at matching ranges of letters and numbers using []. Now we will take a look at some shorter syntax for looking at matching a range of letters and numbers.

Matching all letters and numbers

Previously when we wanted to search for all letter and numbers in the alphabet we had to use [a-z].

While there isn't a shortcut for letters only, there is a shortcut to search for letters and numbers using \w:

let short = /\w/
let myNumber = 23
let myPlayer = "Jordan"
short.test(myNumber) //true
short.test(myPlayer) // true
Enter fullscreen mode Exit fullscreen mode

You can also use /W if you want to search everything but numbers and letters:

let short = /\W/
let myNumber = "45*"
let myPlayer = "Jordan!"
myNumber.match(short) //*
myPlayer.match(short) //!
Enter fullscreen mode Exit fullscreen mode

Match all numbers

If you want to match all the numbers the shortcut for that is \d :

let movieName = "2002: Not A Space Odyssey";
let numRegex = /\d/g; // Change this line
let result = movieName.match(numRegex).length;

console.log(result) // 4
Enter fullscreen mode Exit fullscreen mode

If you want to match all non numbers use \D :

let movieName = "2002: Not A Space Odyssey";
let numRegex = /\D/g; // Change this line
let result = movieName.match(numRegex).length;

console.log(result) //21
Enter fullscreen mode Exit fullscreen mode

Discussion (0)

pic
Editor guide