ToddN
ToddN

Reputation: 2961

Javascript Regex check if URL contains one word AND does NOT contain another

How can one check a url if it contains a specific word, but also check to see if it doesn't contain a word? Its better if I try and display an example:

Do something if the word 'pan' is in the URL, however do NOT do anything when the word 'panini' is in the url:

if (/pan/.test(self.location.href) && (/panini/.test(self.location.href) == null)  {...}

The above first part works fine, but with the second panini part added it of course will not work, anyone have any ideas?

Upvotes: 1

Views: 5226

Answers (5)

Nitzan Volman
Nitzan Volman

Reputation: 1829

var myurl = self.location.href;
if (myurl.indexOf("pan") != -1) && (myurl.indexOf("panini") == -1)
{
   //do something
}

Upvotes: 0

zetlen
zetlen

Reputation: 3619

You can also use negative lookahead, which JS supports in all major browsers.

if ((/pan(?!ini)/).test(myurl)) {

The /pan(?!ini)/ regex matches any "pan" not followed by "ini".

Upvotes: 0

Digital Plane
Digital Plane

Reputation: 38284

test returns a bool, so just use the ! operator:

if (/pan/.test(self.location.href) && !(/panini/.test(self.location.href))  {...}

This could be simplified to use indexOf (should be faster):

if (self.location.href.indexOf("pan") > -1 && self.location.href.indexOf("panini") == -1)
{...}

Additionally, a regex testing for a word can use a word boundary, \b:

/\bpan\b/.test(self.location.href)
//Will match "pan", "pan and food", but not "panini"

Upvotes: 6

Nachshon Schwartz
Nachshon Schwartz

Reputation: 15795

You can use the indexOf property as follows:

url = window.location.href;
if ((url.indexOf("pan") >= 0) && (url.indexOf("panini") < 0)

Upvotes: 0

Blazemonger
Blazemonger

Reputation: 92983

JavaScript's indexOf might solve your problem.

var h=location.href;
if (h.indexOf("pan")>-1 && h.indexOf("panini")==-1) // do stuff

Upvotes: 0

Related Questions