How to check if a string "StartsWith" another string?

1.8k2009 年提問 · sol ·javascriptstringstartswith 主題:字串與正規 → 在 Stack Overflow 看原文 ↗

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 use ECMAScript 6's String.prototype.startsWith() method. It's supported in all major browsers. However, if you want to use it in a browser that is unsupported you'll want to use a shim/polyfill to add it on those browsers. Creating an implementation that complies with all the details laid out in the spec is a little complicated. If you want a faithful shim, use either:

Once you've shimmed the method (or if you're only supporting browsers and JavaScript engines that already have it), you can use it like this:

console.log("Hello World!".startsWith("He")); // true

var haystack = "Hello world";
var prefix = 'orl';
console.log(haystack.startsWith(prefix)); // false

Another alternative with .lastIndexOf:

// does the haystack start with the needle?
haystack.lastIndexOf(needle,0) === 0

This looks backwards through haystack for an occurrence of needle starting from index zero. In other words, it only checks if haystack starts with needle. lastIndexOf provides a second optional parameter 'fromIndex'. If given, the backwards search starts at this given index position and traverses back to index zero. When the second parameter is zero, there are only two possible return values of lastIndexOf -- it either returns 0 (success, the haystack does start with the needle) or -1 (the haystack does not start with the needle).

In principle, this should have performance advantages over some other approaches:

  • It doesn't search the entire haystack.
  • It doesn't create a new temporary string and then immediately discard it.

The "simpler"

haystack.lastIndexOf(needle) === 0 // incorrect!

may seem to give the correct "startsWith" results in some cases. This "simpler" version gives incorrect results if there are two copies of the needle in the string -- then lastIndexOf returns the position of the last copy of that needle, which will be greater than zero, and so will always return False, whether or not the string actually does startWith the needle.