Skip to content
Advertisement

Javascript Regex to match everything after 2nd hyphen

I’m trying to find a JavaScript regex pattern to match on everything after the 2nd instance of the hyphen -

Here is an example:

/property/1-H6205636-1320-Edison-Avenue-Bronx-NY-10461

In this case, I’d like to only match the address so the desired variable to store would be:

1320-Edison-Avenue-Bronx-NY-10461

These characters 1 and H6205636 can change in length so I don’t think a pattern that matches on a specific number of digits would work.

From here, I’d be able to replace the remaining - hyphens with spaces which I think I can manage 🙂

**Open to any methods if regex isn’t the best approach here

Advertisement

Answer

The above regex assume that:

  • /property/ can be any string until it start and end with /
  • 1-H6205636- is any number followed by - then by any string and end with a -.

const str = '/property/1-H6205636-1320-Edison-Avenue-Bronx-NY-10461'
const res = str.match(/^/w+/d+-[^-]+-(.*)$/)[1].replaceAll('-', ' ')
console.log(res)
Advertisement