0

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!

1 Answer 1

1

You need to create a RegExp object if you want to create regex using some string variable:

path.match(new RegExp("\/" + segmentName + "\/([^\/]+)"));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.