luzny
luzny

Reputation: 2400

Check if string does not contain URL segment and match it

How to check if URL string does not contain the following string: test/test/posts/search/1234567, so that when I provide the following URL: test/test/1234567 the match function would return: ["test/test/1234567", "test/test/", "", "1234567"]?

Update:

If I provide /posts/search in URL I would like to omit this regex in re.test(url) function.

// var url = "test/test/posts/search/1234567"; // desired result: null
var url = "test/test/1234567"; // result: ["test/test/1234567", "test/test/", undefined, "1234567"]
var urlPrefix = 'test/test/';
var re = new RegExp('(' + urlPrefix + ')(posts\/search\/)([0-9]+)', 'i');
console.log(url.match(re));

Upvotes: 1

Views: 1017

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627469

You are almost there, you just need to make the second capturing group optional with ? quantifier meaning 0 or 1 occurrence, greedy:

var url = "test/test/posts/search/1234567"; // result: null
var urlPrefix = 'test/test/';
if (!url.includes("posts/search/")) {
   var re = new RegExp('(' + urlPrefix + ')(posts/search/)?([0-9]+)', 'i');
   //                                                     ^    
   console.log(url.match(re));
}
else {
console.log(url + " contains 'posts/search/'!");
}

Upvotes: 1

Related Questions