modpro
modpro

Reputation: 25

How to match string with hypens in JavaScript?

I want to match certain parts of a URL that has the following form:

http://example.com/somepath/this-is-composed-of-hypens-3144/someotherpath

More precisely, I want to match only the part that is composed of all hypens and ends in numbers. So, I want to extract the part this-is-composed-of-hypens-3144 in the above URL. I have something like this:

const re = /[a-z]*-[a-z]*-[0-9]*/gis;
const match = re.exec(url);
return (match && match.length) ? match[0] : null;

However, this works only if there are 2 hypens, however, the number of hypens in my case can be arbitrary. How can I make my regex work for arbitrary number of hypens?

Upvotes: 1

Views: 46

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626903

You may use

/\/([a-z]+(?:-[a-z]+)*-[0-9]+)(?:\/|$)/i

See the regex demo

Details

  • \/ - a / char
  • ([a-z]+(?:-[a-z]*)*-[0-9]+) - Capturing group 1:
    • [a-z]+ - 1+ ASCII letters
    • (?:-[a-z]+)* - 0+ occurrences of - followed with 1+ ASCII letters
  • (?:\/|$) - either / or end of string.

If there can be any word chars, not just ASCII letters, you may replace each [a-z] with \w.

var s = "http://example.com/somepath/this-is-composed-of-hypens-3144/someotherpath";
var m = s.match(/\/([a-z]+(?:-[a-z]+)*-[0-9]+)(?:\/|$)/i);
if (m) {
  console.log(m[1]);
}

Upvotes: 1

Related Questions