Javascript Regex to match everything after 2nd hyphen

Viewed 31

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

2 Answers

You could use .split('-'), remove indexes 0 and 1 using .slice(2), and then .join(' ') the array back together using a space. Though first split on / to get the filename (?) only.

let property = '/property/1-H6205636-1320-Edison-Avenue-Bronx-NY-10461';

// get "1-H6205636-1320-Edison-Avenue-Bronx-NY-10461"
// after splitting, [0] is empty string, [1] is "property", [2] is the rest of the string
let propertyName = property.split('/')[2];

// split by '-' and slice out the first 2 values
let propertySplit = propertyName.split('-').slice(2);

// join it all back together
let propertyAddress = propertySplit.join(' ');

console.log(propertyAddress);

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)

Related