Welcome to WebmasterWorld Guest from 107.20.110.201

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?

     

snowweb

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

5+ Year Member



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.

snowweb

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

5+ Year Member



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 :)

penders

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

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



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) ? '&' : '?';

snowweb

12:50 pm on Oct 5, 2007 (gmt 0)

5+ Year Member



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

 

Featured Threads

Hot Threads This Week

Hot Threads This Month