如何在JavaScript中编写与C#的String.StartsWith等效的代码?

var haystack = 'hello world';
var needle = 'he';

haystack.startsWith(needle) == true

注意:这是一个老问题,正如ECMAScript 2015(ES6)在评论中指出的那样,引入了.startsWith方法。然而,在编写此更新(2015年)时,浏览器支持还远未完成。


当前回答

如果使用startsWith()和endsWith),则必须小心前导空格。下面是一个完整的示例:

var str1 = " Your String Value Here.!! "; // Starts & ends with spaces    
if (str1.startsWith("Your")) { }  // returns FALSE due to the leading spaces…
if (str1.endsWith("Here.!!")) { } // returns FALSE due to trailing spaces…

var str2 = str1.trim(); // Removes all spaces (and other white-space) from start and end of `str1`.
if (str2.startsWith("Your")) { }  // returns TRUE
if (str2.endsWith("Here.!!")) { } // returns TRUE

其他回答

data.substring(0, input.length) === input

可以使用ECMAScript 6的String.product.startsWith()方法。所有主要浏览器都支持它。但是,如果您想在不受支持的浏览器中使用它,则需要使用shim/polyfill将其添加到这些浏览器中。创建一个符合规范中列出的所有细节的实现有点复杂。如果您想要一个忠实的垫片,请使用以下任一方法:

Matthias Bynens的String.prototype.startsWith垫片,或es6垫片,尽可能多地垫片es6规格,包括String.prototype.startsWith。

一旦你填充了这个方法(或者如果你只支持已经有它的浏览器和JavaScript引擎),你可以这样使用它:

console.log(“Hello World!”.startsWith(“He”));//真的var haystack=“你好世界”;var前缀='orl';console.log(haystalk.startsWith(前缀));//假的

根据这里的答案,这是我现在使用的版本,因为它似乎基于JSPerf测试提供了最好的性能(据我所知,它在功能上是完整的)。

if(typeof String.prototype.startsWith != 'function'){
    String.prototype.startsWith = function(str){
        if(str == null) return false;
        var i = str.length;
        if(this.length < i) return false;
        for(--i; (i >= 0) && (this[i] === str[i]); --i) continue;
        return i < 0;
    }
}

这是基于此处的startsWith2:http://jsperf.com/startswith2/6.我添加了一个小的调整,以实现微小的性能改进,此后还添加了一项检查,以检查比较字符串是否为空或未定义,并使用CMS答案中的技术将其转换为添加到字符串原型中。

注意,这个实现不支持Mozilla开发者网络页面中提到的“position”参数,但这似乎并不是ECMAScript建议的一部分。

还可以查看underscore.string.js。它提供了一系列有用的字符串测试和操作方法,包括startsWith方法。从文档中:

startsWith_.startsWith(字符串,开始)此方法检查字符串是否以start开头。_(“image.gif”).startsWith(“image”)=>真

由于这是如此流行,我认为值得指出的是,在ECMA 6中有一种实现该方法的方法,并且为了准备使用“官方”polyfill,以防止将来出现问题和撕裂。

幸运的是,Mozilla的专家为我们提供了一个:

https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith

if (!String.prototype.startsWith) {
    String.prototype.startsWith = function(searchString, position) {
        position = position || 0;
        return this.indexOf(searchString, position) === position;
    };
}

请注意,这有一个优点,即在过渡到ECMA 6时可以优雅地忽略它。