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

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

haystack.startsWith(needle) == true

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


当前回答

我最近问了自己同样的问题。有多种可能的解决方案,以下是3种有效的解决方案:

s.indexOf(启动器)==0s.substr(0,starter.length)==启动器s.lastIndexOf(starter,0)==0(在看到Mark Byers的答案后添加)使用循环:函数startsWith(s,starter){对于(var i=0,cur_c;i<starter.length;i++){cur_c=启动器[i];如果(s[i]!==启动器[i]){return false;}}返回true;}

我还没有遇到使用循环的最后一个解决方案。令人惊讶的是,该解决方案以显著的优势优于前3个解决方案。下面是我为得出这个结论而执行的jsperf测试:http://jsperf.com/startswith2/2

和平

ps:ecmascript 6(harmony)为字符串引入了本机startsWith方法。试想一下,如果他们想到在初始版本中包含这个非常需要的方法,会节省多少时间。

使现代化

正如Steve所指出的(关于这个答案的第一条评论),如果给定的前缀短于整个字符串,上述自定义函数将抛出错误。他已经解决了这个问题,并添加了一个循环优化,可以在http://jsperf.com/startswith2/4.

请注意,Steve包含了两个循环优化,其中第一个显示了更好的性能,因此我将在下面发布代码:

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;
}

其他回答

根据这里的答案,这是我现在使用的版本,因为它似乎基于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建议的一部分。

我不确定javascript,但在typescript中我做了类似的事情

var str = "something";
(<String>str).startsWith("some");

我想它应该也适用于js。我希望这有帮助!

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

我只是想补充一下我对此的看法。

我想我们可以这样使用:

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

if (haystack.indexOf(needle) == 0) {
  // Code if string starts with this substring
}

最佳解决方案:

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