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

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

haystack.startsWith(needle) == true

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


当前回答

以下是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稍快且更简洁,但不可读。

其他回答

使用.lastIndexOf的另一种选择:

haystack.lastIndexOf(needle) === 0

这将在干草堆中向后查看针的出现情况,从干草堆的索引字符串长度开始返回到零。换句话说,它只检查大海捞针是否开始。lastIndexOf提供了第二个可选参数“fromIndex”。如果给定,则反向搜索从该给定索引位置开始,并返回索引零。但是我们不能指定除最后一个索引之外的任何其他fromIndex,否则搜索可能会忽略某些内容。

原则上,这应该比其他一些方法具有性能优势:

它不会搜索整个干草堆。它不会创建新的临时字符串,然后立即丢弃它。

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

我想我们可以这样使用:

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

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

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

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

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

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

以下是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稍快且更简洁,但不可读。