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.
You can also return all members of an array that start with a string by creating your own prototype / extension to the the array prototype, aka
And to use it:
I just wanted to add my opinion about this.
I think we can just use like this:
Without a helper function, just using regex's
.test
method:To do this with a dynamic string rather than a hardcoded one (assuming that the string will not contain any regexp control characters):
You should check out Is there a RegExp.escape function in Javascript? if the possibility exists that regexp control characters appear in the string.