AptlyA
AptlyA

Reputation: 7

Matching Words With or Without Hyphens

So I'm basically trying to match words in a string that may or may not contain hyphens. For instance, in the strings below:

let firstStr = "filter-table";
let secondStr = "filter-second-table";

"filter-" is a required keyword, and so, I'd want to match the words containing "filter-" followed by any character/word (hyphenated or not).

Using the following:

secondStr.match(/filter-\w+/);

"firstStr" matches correctly but not "secondStr". "secondStr" only matches "filter-second" and not the hyphenated word after - "filter-second-table".

I'd want to be able to match any potential hyphenated word as in "second-table".

Upvotes: 1

Views: 31

Answers (1)

Richard Henage
Richard Henage

Reputation: 1798

Make a group that can be matched multiple times like this: /filter(-\w+)+/

myTest("filter-table");
myTest("filter-second-table");
myTest("filter-awesome-second-table");


function myTest(string){
  let matches = string.match(/filter(-\w+)+/)
  console.log(string, matches ? "matches!" : "doesn't match")
}

Upvotes: 1

Related Questions