如何在JavaScript中编写与C#的String.StartsWith等效的代码?
var haystack = 'hello world';
var needle = 'he';
haystack.startsWith(needle) == true
注意:这是一个老问题,正如ECMAScript 2015(ES6)在评论中指出的那样,引入了.startsWith方法。然而,在编写此更新(2015年)时,浏览器支持还远未完成。
如何在JavaScript中编写与C#的String.StartsWith等效的代码?
var haystack = 'hello world';
var needle = 'he';
haystack.startsWith(needle) == true
注意:这是一个老问题,正如ECMAScript 2015(ES6)在评论中指出的那样,引入了.startsWith方法。然而,在编写此更新(2015年)时,浏览器支持还远未完成。
当前回答
data.substring(0, input.length) === input
其他回答
我不确定javascript,但在typescript中我做了类似的事情
var str = "something";
(<String>str).startsWith("some");
我想它应该也适用于js。我希望这有帮助!
data.substring(0, input.length) === input
var str = 'hol';
var data = 'hola mundo';
if (data.length >= str.length && data.substring(0, str.length) == str)
return true;
else
return false;
可以使用ECMAScript 6的String.product.startsWith()方法。所有主要浏览器都支持它。但是,如果您想在不受支持的浏览器中使用它,则需要使用shim/polyfill将其添加到这些浏览器中。创建一个符合规范中列出的所有细节的实现有点复杂。如果您想要一个忠实的垫片,请使用以下任一方法:
Matthias Bynens的String.prototype.startsWith垫片,或es6垫片,尽可能多地垫片es6规格,包括String.prototype.startsWith。
一旦你填充了这个方法(或者如果你只支持已经有它的浏览器和JavaScript引擎),你可以这样使用它:
console.log(“Hello World!”.startsWith(“He”));//真的var haystack=“你好世界”;var前缀='orl';console.log(haystalk.startsWith(前缀));//假的
最佳解决方案:
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