简体   繁体   English

使用JavaScript,我需要帮助将变量连接为正则表达式

[英]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. 我正在编写一个JavaScript函数,以从出现在指定段右侧的URL中提取段。

For instance, if this is my URL ... 例如,如果这是我的网址...

mysite.com/cat/12/dog/34?test=123 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. ...我希望能够将'cat'传递给函数并获取12,然后将'dog'传递给函数并使其返回34。我在StackOverflow上找到了此答案以提取URL段,但是使用字符串文字。 And I'm having difficulty concatenating a passed in value. 而且,我很难将传递的值连接起来。

jQuery to parse our a part of a url path jQuery解析我们的URL路径的一部分

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. 在这种情况下,我不想将'cat'硬编码到模式匹配中,而是希望将'cat'传递到segmentName参数中,并使之与正则表达式匹配。

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/ 这是一个jsfiddle示例: http : //jsfiddle.net/Stormjack/2Ebsv/

Thanks for your help! 谢谢你的帮助!

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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