如何在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年)时,浏览器支持还远未完成。
当前回答
我只是想补充一下我对此的看法。
我想我们可以这样使用:
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
如果没有助手函数,只需使用regex的.test方法:
/^He/.test('Hello world')
要使用动态字符串而不是硬编码字符串(假设字符串不包含任何正则表达式控制字符)执行此操作:
new RegExp('^' + needle).test(haystack)
你应该看看Javascript中是否有RegExp.escape函数?如果存在正则表达式控制字符出现在字符串中的可能性。
还可以查看underscore.string.js。它提供了一系列有用的字符串测试和操作方法,包括startsWith方法。从文档中:
startsWith_.startsWith(字符串,开始)此方法检查字符串是否以start开头。_(“image.gif”).startsWith(“image”)=>真
var str = 'hol';
var data = 'hola mundo';
if (data.length >= str.length && data.substring(0, str.length) == str)
return true;
else
return false;
我只是想补充一下我对此的看法。
我想我们可以这样使用:
var haystack = 'hello world';
var needle = 'he';
if (haystack.indexOf(needle) == 0) {
// Code if string starts with this substring
}