views:

36

answers:

4

I have the following if statement in javascript. I am targeting pages which have art-8 in url.

Sample url is like this,

http://www.mywebsite.com/art-8.asp?id=435&iPageID=43

However this will pick up an url with cart-8 and I don't want that.

I want only select art-8 in url not cart-8.

How should I change it?

if (location.pathname.indexOf('art-8') > 0){

...............

Do I need regex?

Thanks in advance.

A: 

What about this regexp?

[^c]art-8
thejh
What if the string is just `"art-8"`?
Gabe
The pathname part is always going to begin with a slash, at least for HTTP.
idealmachine
+1  A: 
if (/\/art-8\/?$/.test(location.pathname)) {
    ...
}

will match any pathname ending in /art-8 or /art-8/. Or splitting the pathname into its component parts:

var parts = location.pathname.split('/').slice(1);
if(parts[parts.length - 1] == '') parts = parts.slice(0, -1);
if(parts[parts.length - 1] == 'art-8') {
    ...
}

EDIT: If art-8 need not be at the end, but there is a slash before it:

if (/\/art-8/.test(location.pathname)) {
    ...
}

Or if there isn't necessarily a slash before it, but you just want to look for art-8 without a c before it (pathname will always begin with a slash, so there will always be at least one character before and this will work):

if (/[^c]art-8/.test(location.pathname)) {
    ...
}

Note that pathname does not include the ? and what comes after it, so even the first two examples I gave should work for the specific example URL you gave if you add .asp just after the 8.

idealmachine
art-8 is a part of url, not at the end
shin
Is .test() a js function?
shin
@shin: Yes, it is a method of RegExp objects that returns `true` if the regex matches the given string and `false` if it does not. Both `/test/` and `new RegExp("test")` are ways to write regexes in JavaScript.
idealmachine
Thanks. solved.
shin
A: 

If you're only concerned with individual path segments, and you want to find only paths that contain at least one path segment that is exactly equal to 'art-8', then you could do this:

if (location.pathname.indexOf('/art-8/') > 0) {

which would work for all cases except the case where 'art-8' was at the end, without a trailing slash. You could add another check for the special case, without the trailing slash, and including a check to be sure the index places it at the end of the line.

but if you're on modern browsers, with RegExp support, then all you need is:

var rx=new RegExp("/art-8(/|$)");
if( rx.test(location.pathname) ) {
  ...
}

w3schools has a fairly comprehensive reference for the javascript RegExp object

Lee