DEV Community

SCDan0624
SCDan0624

Posted on

2 2 1

Javascript Regex Part 3 More Character Matching

Negated character set

Negated character sets are a set of characters you do not want to match. To create a negated character set you place ^ after the opening bracket. Here is an example:

let mySample = "Hello"
let myRegex = /[^aeiou]/gi
let result  = mySample.match(myRegex)

console.log(result) // [ 'H', 'l', 'l' ]
Enter fullscreen mode Exit fullscreen mode

Match characters that occur 0 or more times

To search for characters that occur 0 or more times you use an * after the word:

let happy = "yessssss"
let myRegex = /yes/
let myRegex2 = /yes*/
happy.match(myRegex) //'yes'
happy.match(myRegex2) // 'yessssss'

Enter fullscreen mode Exit fullscreen mode

Match characters that occur 1 or more times

You can also match characters that occur 1 or more times using the + symbol after the word:

let happy = "aabc"
let myRegex = /a/
let myRegex2 = /a+/
happy.match(myRegex) //'a'
happy.match(myRegex2) //'aa'
Enter fullscreen mode Exit fullscreen mode

Lazy matching

A lazy match finds the smallest part of the string that satisfies the regex pattern.

To use lazy matching put a ? after the characters you are searching for:

let happy = "basketball"
let myRegex = /b[a-k]l/ // not lazy matching or 'greedy matching'
let myRegex2 = /b[a-k]l?/ //lazy matching
happy.match(myRegex) //'bal'
happy.match(myRegex2) //'ba'
Enter fullscreen mode Exit fullscreen mode

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay