如何在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年)时,浏览器支持还远未完成。
当前回答
如果使用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
其他回答
最佳解决方案:
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
使用.lastIndexOf的另一种选择:
haystack.lastIndexOf(needle) === 0
这将在干草堆中向后查看针的出现情况,从干草堆的索引字符串长度开始返回到零。换句话说,它只检查大海捞针是否开始。lastIndexOf提供了第二个可选参数“fromIndex”。如果给定,则反向搜索从该给定索引位置开始,并返回索引零。但是我们不能指定除最后一个索引之外的任何其他fromIndex,否则搜索可能会忽略某些内容。
原则上,这应该比其他一些方法具有性能优势:
它不会搜索整个干草堆。它不会创建新的临时字符串,然后立即丢弃它。
如果使用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
我刚刚了解了这个字符串库:
http://stringjs.com/
包括js文件,然后像这样使用S变量:
S('hi there').endsWith('hi there')
它也可以通过安装在NodeJS中使用:
npm install string
然后要求它作为S变量:
var S = require('string');
如果你不喜欢这个字符串库的话,这个网页也有指向其他字符串库的链接。
如果没有助手函数,只需使用regex的.test方法:
/^He/.test('Hello world')
要使用动态字符串而不是硬编码字符串(假设字符串不包含任何正则表达式控制字符)执行此操作:
new RegExp('^' + needle).test(haystack)
你应该看看Javascript中是否有RegExp.escape函数?如果存在正则表达式控制字符出现在字符串中的可能性。