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

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

haystack.startsWith(needle) == true

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


当前回答

由于这是如此流行,我认为值得指出的是,在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时可以优雅地忽略它。

其他回答

最好的性能解决方案是停止使用库调用,只需认识到您使用的是两个阵列。手动实现既短又快,比我在这里看到的其他解决方案都快。

function startsWith2(str, prefix) {
    if (str.length < prefix.length)
        return false;
    for (var i = prefix.length - 1; (i >= 0) && (str[i] === prefix[i]); --i)
        continue;
    return i < 0;
}

有关性能比较(成功与失败),请参阅http://jsperf.com/startswith2/4.(确保您检查了可能胜过我的更高版本。)

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

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

最佳解决方案:

function startsWith(str, word) {
    return str.lastIndexOf(word, 0) === 0;
}

这里是endsWith,如果你也需要:

function endsWith(str, word) {
    return str.indexOf(word, str.length - word.length) !== -1;
}

对于喜欢将其原型化为字符串的用户:

String.prototype.startsWith || (String.prototype.startsWith = function(word) {
    return this.lastIndexOf(word, 0) === 0;
});

String.prototype.endsWith   || (String.prototype.endsWith = function(word) {
    return this.indexOf(word, this.length - word.length) !== -1;
});

用法:

"abc".startsWith("ab")
true
"c".ensdWith("c") 
true

使用方法:

startsWith("aaa", "a")
true
startsWith("aaa", "ab")
false
startsWith("abc", "abc")
true
startsWith("abc", "c")
false
startsWith("abc", "a")
true
startsWith("abc", "ba")
false
startsWith("abc", "ab")
true

如果使用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

以下是CMS解决方案的一个小改进:

if(!String.prototype.startsWith){
    String.prototype.startsWith = function (str) {
        return !this.indexOf(str);
    }
}

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

 var data = "Hello world";
 var input = 'He';
 data.startsWith(input); // true

检查该函数是否已存在,以防将来的浏览器以本机代码实现该函数,或者该函数是否由其他库实现。例如,原型库已经实现了这个函数。

使用!比==0稍快且更简洁,但不可读。