Eddie Martinez
Eddie Martinez

Reputation: 13910

how to get only fully matched string from match

I need to match "test" or "test," from a string like

"test, testhellowowo, wowtest,"

Attempt 1

test[,]?

it will match all three since all of the string include the test regardless what comes after.

Attempt 2

^test[,]?$

it won't match any unless the string is test or test,

Expected results

"test, testhellowowo, wowtest,".match(x) // should match `test,` 
"testhellowowo, wowtest,".match(x)  // should not match anything

Upvotes: 1

Views: 36

Answers (2)

eric
eric

Reputation: 454

If you need to include the punctuation mark you could also do /^test[,]?$/gm

^ matches beginning of string $ matches end of string

Upvotes: 0

adeneo
adeneo

Reputation: 318302

You can use word boundaries

/\btest\b/g

They match at

  • Before the first character in the string, if the first character is a word character.
  • After the last character in the string, if the last character is a word character.
  • Between two characters in the string, where one is a word character and the other is not a word character.

Upvotes: 3

Related Questions