Alex Wardrop
Alex Wardrop

Reputation: 15

Is there a more efficient way to write this REGEX to return whole words containing certain letters?

Ok so here is some REGEX:

/\w*a\w*/g (with global flag)

This is to find any word that has an "a". (example: matches apple, ark and petal in this array P {ent, apple, peter, ark, petal}

Is there anyone who can think of a more efficient way to write this? Many thanks in advance, Alex

Upvotes: 0

Views: 44

Answers (3)

unigg
unigg

Reputation: 464

I use [^\W]*a[^\W]*to match all words containing the letter a

Upvotes: 0

mplungjan
mplungjan

Reputation: 177960

Or not use a regex, this is more readable

const letter = "a",
arr = ["ent", "apple", "peter", "ark", "petal"];
console.log(arr.filter(word=>word.includes(letter)))

Upvotes: 1

The fourth bird
The fourth bird

Reputation: 163362

You can exclude a from the word characters until you have found it using a negated character class where \W matches any non word character.

[^\Wa]*a\w*
  • [^\Wa]* Optionally repeat any word chars without a
  • a\w* Match a and optional word chars

Regex demo

Upvotes: 1

Related Questions