views:

53

answers:

3

How would I go about writing this if statement in javascript?

if(url == "http://www.google.com/" && "*")
  { ... }

The * needs to be flexible and accept anything added onto the first variable... If no value is assigned to *, the condition must still be true...

+3  A: 

You can use .indexOf(), like this:

if(url.indexOf("http://www.google.com/") == 0)

The meaning of this is "url starts with http://www.google.com/". Or depending on what you're after, a regex may be better, for example:

if(/^http:\/\/www.google.com\//​​​​​​​​.test(url))
Nick Craver
thanks... spelling error on `indexOf` otherwise it works!
David
A: 

Javascript can already do this... the only catch is that since you're using the logical AND operator (&&) you'll need to preprocess the second condition so that it evaluates to TRUE if the condition is otherwise null.

Brian Driscoll
+2  A: 

You can use this startsWith method:

String.prototype.startsWith = function(prefix) {
    return this.substr(0, prefix.length) === prefix;
};

Then you can use that method on url like this:

if (url.startsWith("http://www.google.com/"))
Gumbo