How would I write the equivalent of C#'s String.StartsWith
in JavaScript?
var haystack = 'hello world';
var needle = 'he';
haystack.startsWith(needle) == true
Note: This is an old question, and as pointed out in the comments ECMAScript 2015 (ES6) introduced the .startsWith
method. However, at the time of writing this update (2015) browser support is far from complete.
Best solution:
And here is endsWith if you need that too:
For those that prefer to prototype it into String:
Usage:
Also check out underscore.string.js. It comes with a bunch of useful string testing and manipulation methods, including a
startsWith
method. From the docs:Based on the answers here, this is the version I am now using, as it seems to give the best performance based on JSPerf testing (and is functionally complete as far as I can tell).
This was based on startsWith2 from here: http://jsperf.com/startswith2/6. I added a small tweak for a tiny performance improvement, and have since also added a check for the comparison string being null or undefined, and converted it to add to the String prototype using the technique in CMS's answer.
Note that this implementation doesn't support the "position" parameter which is mentioned in this Mozilla Developer Network page, but that doesn't seem to be part of the ECMAScript proposal anyway.
I just learned about this string library:
http://stringjs.com/
Include the js file and then use the
S
variable like this:It can also be used in NodeJS by installing it:
Then requiring it as the
S
variable:The web page also has links to alternate string libraries, if this one doesn't take your fancy.
Here is a minor improvement to CMS's solution:
Checking whether the function already exists in case a future browser implements it in native code or if it is implemented by another library. For example, the Prototype Library implements this function already.
Using
!
is slightly faster and more concise than=== 0
though not as readable.