简体   繁体   中英

With JavaScript, I need help concatenating a variable into a regular expression

I'm writing a JavaScript function to extract a segment out of a URL that appears to the right of a designated segment.

For instance, if this is my URL ...

mysite.com/cat/12/dog/34?test=123

... I would like to be able to pass 'cat' to the function and get 12, and later pass 'dog' to the function and have it return 34. I found this answer on StackOverflow to extract the URL segment, but it uses a string literal. And I'm having difficulty concatenating a passed in value.

jQuery to parse our a part of a url path

Here is my code. In this, rather than hard coding 'cat' into the pattern match, I would like to pass 'cat' into the segmentName parameter and have the regular expression match on that.

var url = "www.mysite.com/cat/12/dog/34?test=123";
alert(getNextSegmentAfterSegmentName(url, 'cat'));

function getNextSegmentAfterSegmentName(currentPath, segmentName) {
   var nextSegment = "";
   segmentName = segmentName.toLowerCase();
   //var currentPath = window.location.pathname.toLowerCase();
   if (currentPath.indexOf(segmentName) >= 0) {
      var path = currentPath.split('?')[0]; // Strip querystring

      // How do I concatenate segmentName into this?
      var matches = path.match(/\/cat\/([^\/]+)/);

      if (matches) {
         nextSegment = matches[1];
      }
   }
   return nextSegment;
}

Here is a jsfiddle example: http://jsfiddle.net/Stormjack/2Ebsv/

Thanks for your help!

如果要使用某些字符串变量创建正则表达式,则需要创建一个RegExp对象:

path.match(new RegExp("\/" + segmentName + "\/([^\/]+)"));

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