2

Possible Duplicate:
javascript - check if string begins with something?

I've read in this post that you can use ^= to check if a string begins with something.

I've fiddled with this example:

var foo = "something-something";
if(foo ^= "something") {
    alert("works!");
}
else{
    alert("doesn't work :(");
}

And it doesn't work - does anyone how to do this?

jsfiddle example here: http://jsfiddle.net/timkl/M6dEM/

Community
  • 1
  • 1
timkl
  • 3,299
  • 12
  • 57
  • 71

3 Answers3

10

I think, perhaps, you were thinking of:

var x = "hello world!"
if (x.match(/^hello/)) {
   alert("I start with it!")
}

This uses an anchored (^) regular expression: it must find "hello" at the start of the input to match.

On the other hand, x ^= "foo" is the same as x = x ^ "foo", or a bit-wise exclusive or. In this case that is equivalent to x = "something-something" ^ "something" -> x = 0 ^ 0 -> 0 (which is a falsey value, and never true).

Happy coding.

8
   var foo = "something-something";
if(foo.indexOf("something") === 0) {
    alert("works!");
}
else{
    alert("doesn't work :(");
}

See updated jsfiddle http://jsfiddle.net/M6dEM/3/

Chuck Norris
  • 15,207
  • 15
  • 92
  • 123
5

Use substring() method.

if(foo.substring(0,"something".length) == "something") {
    alert("works!");
}
else{
    alert("doesn't work :(");
}

I edited my answer and replaced "9" with "something".length so now there's no hardcode anymore.

shift66
  • 11,760
  • 13
  • 50
  • 83