Welcome to WebmasterWorld Guest from 54.145.118.24

Forum Moderators: open

Message Too Old, No Replies

determine whether url passed to JS, has a '?' in it.

should I use regex or straight javascript?

     
11:08 am on Oct 5, 2007 (gmt 0)

Junior Member

10+ Year Member

joined:Apr 20, 2006
posts: 56
votes: 0


Hi, I'm trying to determine whether the url passed to javascript script contains a question mark.

I've tried the following:


if (url.match("?") == "?")
{
var $append = '&' ;
}
else
{
var $append = '?' ;
}

It said the '?' was an "invalid quantifier".

So I decided to attempt a regex (not my speciality!)


if (RegEx.match(url,"\?"))
{
var $append = '&' ;
}
else
{
var $append = '?' ;
}

This doesn't report an error but it doesn't seem to work either!

Please can someone help me?

Thanks

Peter.

11:28 am on Oct 5, 2007 (gmt 0)

Junior Member

10+ Year Member

joined:Apr 20, 2006
posts: 56
votes: 0


Hey Guys! STOP! I've fixed it :)

Apart from me being muppet and specifying the variable like php variable with a '$', I also got the if statement sorted after fiddling a bit longer..


if (url.match("\\?") == '?')
{
var append = '&';
}
else
{
var append = '?';
}

That's what is looks like now.

Thanks anyways :)

11:58 am on Oct 5, 2007 (gmt 0)

Senior Member

WebmasterWorld Senior Member penders is a WebmasterWorld Top Contributor of All Time 10+ Year Member Top Contributors Of The Month

joined:July 3, 2006
posts: 3123
votes: 0


Apart from me being muppet and specifying the variable like php variable with a '$'....

Just to note, it is perfectly valid to use PHP style variables (with a '$' prefix) in JS. In fact more developers seem to be doing this.

should I use regex or straight javascript?

You are using a regular expression in your above example, but I think it would perhaps be more efficient to use a 'straight javascript' function. A regular expression can be a bit processor hungry for simple searches, particularly if you are doing many of them.

So, you could use:

var append = (url.indexOf('?') > -1) ? '&' : '?';
12:50 pm on Oct 5, 2007 (gmt 0)

Junior Member

10+ Year Member

joined:Apr 20, 2006
posts: 56
votes: 0


That's very impressive! It worked too!

I didn't know that I could use php style variables either, so thanks for putting me straight on that. I can understand why. As I spend about 80% of my coding time in PHP, I get used to recognizing variables with a $ in front of them. It will certainly help to be consistent.

Thanks all round.

Peter

 

Join The Conversation

Moderators and Top Contributors

Hot Threads This Week

Featured Threads

Free SEO Tools

Hire Expert Members