0

I want javascript regex for a question mark in url to work I have 3 urls

the requirement is to create a regex for first 2 urls and not the third one.

1st url -- https://www.abc.xyz/search/?collection=check&query=activity
2nd url-- https://www.abc.xyz/search?collection=check&query=activity
3rd url -- https://abc.xyz/searchapps/?query=activity

(/\/search\//.test(window.location.pathname)) works for 1st but not for 2nd

if I use (/\/search?/.test(window.location.pathname) it works for 2nd url However the problem is it also matches 3rd url https://abc.xyz/searchapps/?query=activity

  • `/\/search?/` matches `/search` and `/searc` - it doesn't match the question mark, since it's a special character. – VLAZ Dec 13 '18 at 13:24
  • thanks @vlaz but how to make it work for first 2 url and not third one – Ramaiya v raghvendra Dec 13 '18 at 13:25
  • Escape the question mark. Same as how you did with with the forward slash. – VLAZ Dec 13 '18 at 13:26
  • Escape it - `/\/search\?/`, see [this answer](https://stackoverflow.com/a/890001/3832970) – Wiktor Stribiżew Dec 13 '18 at 13:26
  • i tried /\/search\?/ it doesnt work – Ramaiya v raghvendra Dec 13 '18 at 13:28
  • /\/search\?/ will look for specifically "/search?", is that not what you want? Edit: I see the difference between the first two lines, will update – Chris Dec 13 '18 at 13:28
  • i did it in the console but it doesnt print test if(/\/search\?/.test(window.location.pathname))console.log('test'); – Ramaiya v raghvendra Dec 13 '18 at 13:28
  • `/\/search\/?\?/` - optional backslash at the end and a mandatory question mark. Although it seems easier to parse the URL instead of do regex matches. – VLAZ Dec 13 '18 at 13:34
  • `/\/search(\/?)\?/` addresses /search/? and /search?, like the first two examples you gave. If that doesn't work there may be another issue – Chris Dec 13 '18 at 13:34
  • tried it in the console and it doesnt work so pls suggest if(/\/search(\/?)\?/.test(window.location.pathname))console.log('test'); hit the url and put this in console you won't see 'test' getting printed – Ramaiya v raghvendra Dec 13 '18 at 13:39
  • `window.location.pathname` will NOT give you the query string, it will just return `/search`. You can see that if you do `console.log(window.location.pathname)`. And you can see the regex working if you try `console.log(/\/search(\/?)\?/.test("https://www.abc.xyz/search/?collection=check&query=activity"))` – VLAZ Dec 13 '18 at 13:45
  • thank you @vlaz i made it to window.location.href and it worked if(/\/search(\/?)\?/.test(window.location.href))console.log('test'); – Ramaiya v raghvendra Dec 13 '18 at 13:49

0 Answers0