简体   繁体   中英

Javascript Regex Match string

Inputs or spot in the function (always be something along the line):

Washington, T. rush for 3 yards to the MT0

I want to get the text " to the MT0 "

"MT" will be matched with either var homeacrynm or awayacrynm that I will initialize before the function call. Here is what I have tried so far:

getEndSpotEugene: function(spot)
    {
        var regex = new RegExp("to the +("+homeacrynm+"|"+awayacrynm+")?([0-9]{1,2})","g");
        var matches = spot.match(regex);
        if (matches)
        {
            pos = matches[matches.length-1]
            matches = pos.match(/to the ([A-Z]+)?([0-9]{1,2})/);
            if (!matches[1])
            {
                matches=[pos,"V",50];   
            }
        }
        else
        {
            return -1;  
        }
        var acr = matches[1];
        var yard = matches[2];
        if (acr == homeacrynm) 
            return "H"+yard;
        else
            return "V"+yard;
    },

For example (One simple case):

homeacrynm = "MT"
var giveMe = getEndSpotEugene("Washington, T. rush for 3 yards to the MT11")

giveMe should be H11 but its not for some reason.

I am not quite sure where its wrong either. Do you guys see anything that I am missing? Thank you!

I made some logs and explicitly declared homeacrynm and awayacrynm like so:

  var homeacrynm = "MT";
  var awayacrynm = "H";
  var getEndSpotEugene = function(spot)
  {
      var regex = new RegExp("to the +("+homeacrynm+"|"+awayacrynm+")?([0-9]{1,2})","g");
      console.log(regex);
      var matches = spot.match(regex);
      console.log(matches);
      if (matches)
      {
          pos = matches[matches.length-1]
          matches = pos.match(/to the ([A-Z]+)?([0-9]{1,2})/);
          if (!matches[1])
          {
              matches=[pos,"V",50];   
          }
      }
      else
      {
          return -1;  
      }
      var acr = matches[1];
      var yard = matches[2];
      console.log(acr);
      console.log(yard);          
      if (acr == homeacrynm) 
          return "H"+yard;
      else
          return "V"+yard;
  }

Strangely, I get H11 as you expect! What are you getting?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM