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

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, but it's not yet supported in all browsers. You'll want to use a shim/polyfill to add it on browsers that don't support it. Creating an implementation that complies with all the details laid out in the spec is a little complicated, and the version defined in this answer won't do; if you want a faithful shim, use either:

  • Matthias Bynens's String.prototype.startsWith shim, or
  • The es6-shim, which shims as much of the ES6 spec as possible, including String.prototype.startsWith .
  • 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:

    "Hello World!".startsWith("He"); // true
    
    var haystack = "Hello world";
    var prefix = 'orl';
    haystack.startsWith(prefix); // false
    
    链接地址: http://www.djcxy.com/p/74016.html

    上一篇: 如何比较两个字符串与只在python中的一些字符

    下一篇: 如何检查一个字符串“StartsWith”是否是另一个字符串?