Trying To Match Url Pathname With Regex
I'm trying to match this: /Wedding to /Wedding/Areas /Wedding being the word to match. I think I'm not escaping the character correctly. var pattern = new RegExp('^/' + href + '*$
Solution 1:
var pattern = newRegExp("^/" + href + ".*$");
you forget the dot before the asterisk
but a better regex would be :
"^/" + href + "/.*$"
to be sure to have a subpath and not a partial word
Solution 2:
You can use the following regex to match the path name portion of a url:
var pathNameRegex = /^(?:(?:\w{3,5}:)?\/\/[^\/]+)?(?:\/|^)((?:[^#\.\/:?\n\r]+\/?)+(?=\?|#|$|\.|\/))/;
var matches = "https://stackoverflow.com/questions/9946435/trying-to-match-url-pathname-with-regex?rq=1".match(pathNameRegex);
//The last next of matches will have "questions/9946435/trying-to-match-url-pathname-with-regex"console.log(matches[matches.length - 1]);
matches = "/questions/9946435/trying-to-match-url-pathname-with-regex?rq=1".match(pathNameRegex);
//The last next of matches will have "questions/9946435/trying-to-match-url-pathname-with-regex"console.log(matches[matches.length - 1]);
matches = "//stackoverflow.com/questions/9946435/trying-to-match-url-pathname-with-regex?rq=1".match(pathNameRegex);
//The last next of matches will have "questions/9946435/trying-to-match-url-pathname-with-regex"console.log(matches[matches.length - 1]);
Post a Comment for "Trying To Match Url Pathname With Regex"