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

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

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

haystack.startsWith(needle) == true

注意:这是一个古老的问题,正如评论中指出的ECMAScript 2015(ES6)引入了该.startsWith方法。但是,在撰写此更新(2015)时,浏览器支持还远远没有完成

蛋蛋L2020/03/09 20:02:23

I am not sure for javascript but in typescript i did something like

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

I guess it should work on js too. I hope it helps!

小小Pro2020/03/09 20:02:23

If you are working with startsWith() and endsWith() then you have to be careful about leading spaces. Here is a complete example:

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
凯JinJin2020/03/09 20:02:23

Also check out underscore.string.js. It comes with a bunch of useful string testing and manipulation methods, including a startsWith method. From the docs:

startsWith _.startsWith(string, starts)

This method checks whether string starts with starts.

_("image.gif").startsWith("image")
=> true
西门逆天2020/03/09 20:02:23
data.substring(0, input.length) === input
Davaid阳光小卤蛋2020/03/09 20:02:23

Best solution:

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

Used:

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

And here is endsWith if you need that too:

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

For those that prefer to prototype it into String:

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

Usage:

"abc".startsWith("ab")
true
"c".ensdWith("c") 
true
Itachi达蒙Green2020/03/09 20:02:23

另一种选择是.lastIndexOf

haystack.lastIndexOf(needle, 0) === 0

这看起来向后通过haystack为的发生needle,从指数开始0haystack换句话说,它仅检查是否haystack以开头needle

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

  • 它不会搜索整个haystack
  • 它不会创建新的临时字符串,然后立即将其丢弃。