如何在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年)时,浏览器支持还远未完成。
当前回答
我刚刚了解了这个字符串库:
http://stringjs.com/
包括js文件,然后像这样使用S变量:
S('hi there').endsWith('hi there')
它也可以通过安装在NodeJS中使用:
npm install string
然后要求它作为S变量:
var S = require('string');
如果你不喜欢这个字符串库的话,这个网页也有指向其他字符串库的链接。
其他回答
var str = 'hol';
var data = 'hola mundo';
if (data.length >= str.length && data.substring(0, str.length) == str)
return true;
else
return false;
由于这是如此流行,我认为值得指出的是,在ECMA 6中有一种实现该方法的方法,并且为了准备使用“官方”polyfill,以防止将来出现问题和撕裂。
幸运的是,Mozilla的专家为我们提供了一个:
https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith
if (!String.prototype.startsWith) {
String.prototype.startsWith = function(searchString, position) {
position = position || 0;
return this.indexOf(searchString, position) === position;
};
}
请注意,这有一个优点,即在过渡到ECMA 6时可以优雅地忽略它。
最佳解决方案:
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
data.substring(0, input.length) === input
我刚刚了解了这个字符串库:
http://stringjs.com/
包括js文件,然后像这样使用S变量:
S('hi there').endsWith('hi there')
它也可以通过安装在NodeJS中使用:
npm install string
然后要求它作为S变量:
var S = require('string');
如果你不喜欢这个字符串库的话,这个网页也有指向其他字符串库的链接。