Search code examples
javascriptregexregex-group

Extracting highways from a string using regular expression matcher


I am using regular expression matcher to extract portion of string from a text.

For e.g. Here is the text :

var str = "I-35 South / US-290 West"

I would like to extract two strings,

  1. I-35 South
  2. US-290 West.

I tried the below pattern, its returning true on test method. However not returning expected matches.

var pattern = /^(I|US|TX)-\d{1,3}.*$/

str.match(pattern)

Returns

  1. "I-35 South / US-290 West"
  2. "I"

If I remove ".*" matching is not happening.

Any help appreciated.


Solution

  • Using matches we can try:

    var str = "I-35 South / US-290 West";
    var highways = str.match(/[A-Z]+-\d+ \w+/g);
    console.log(highways);

    Note that if your input would always be a slash-separated list of highways, you might as well just split on that separator:

    var str = "I-35 South / US-290 West";
    var highways = str.split(/\s*\/\s*/);
    console.log(highways);