如何String.StartsWith
在JavaScript中编写等效于C#的代码?
var haystack = 'hello world';
var needle = 'he';
haystack.startsWith(needle) == true
注意:这是一个古老的问题,正如评论中指出的ECMAScript 2015(ES6)引入了该.startsWith
方法。但是,在撰写此更新(2015)时,浏览器支持还远远没有完成。
如何String.StartsWith
在JavaScript中编写等效于C#的代码?
var haystack = 'hello world';
var needle = 'he';
haystack.startsWith(needle) == true
注意:这是一个古老的问题,正如评论中指出的ECMAScript 2015(ES6)引入了该.startsWith
方法。但是,在撰写此更新(2015)时,浏览器支持还远远没有完成。
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
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 withstarts
._("image.gif").startsWith("image") => true
data.substring(0, input.length) === input
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
另一种选择是.lastIndexOf
:
haystack.lastIndexOf(needle, 0) === 0
这看起来向后通过haystack
为的发生needle
,从指数开始0
的haystack
。换句话说,它仅检查是否haystack
以开头needle
。
原则上,与其他方法相比,这应该具有性能优势:
haystack
。
I am not sure for javascript but in typescript i did something like
I guess it should work on js too. I hope it helps!