Alex
Alex

Reputation: 1606

Match only one URL with Javascript

I have this code:

if (!window.location.href.match(/\?snake=/)) {

Which redirects the user if you go to site.com/snake. The problem is that it matches another URL starting with the same keyword and I get an endless loop:

site.com/snake-mobile

How can I avoid that? And only match a URL which ends with snake?

Upvotes: 2

Views: 51

Answers (2)

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123397

Use the $ boundary character at the end of your regexp

.match(/\/snake$/)) 

From MDN

$

Matches end of input. If the multiline flag is set to true, also matches immediately before a line break character.

Upvotes: 1

Sorikairo
Sorikairo

Reputation: 798

You could use href.endsWith("snake"). It used endsWith ECMAS 6 function which is very usefull but it isn't compatible with all web Browsers.

Upvotes: 1

Related Questions