我有一个Web应用程序。在其中一个页面中,我遍历所有HTML元素ID,无论其中一个是否以指定的字符串结尾。每个JS函数都可以在页面上运行,但是“ endsWith”函数不起作用。我真的不明白这件事。有人可以帮忙吗?
var str = "To be, or not to be, that is the question.";
alert(str.endsWith("question."));
Run Code Online (Sandbox Code Playgroud)
上面的简单JS代码根本行不通吗?
如这篇文章所说:http://rickyrosario.com/blog/javascript-startswith-and-endswith-implementation-for-strings/
var str = "To be, or not to be, that is the question.";
function strEndsWith(str, suffix) {
return str.match(suffix+"$")==suffix;
}
alert(strEndsWith(str,"question."));
Run Code Online (Sandbox Code Playgroud)
如果以提供的后缀结尾,则将返回true。
编辑
在这里检查之前也有类似的问题
答案说
var str = "To be, or not to be, that is the question$";
String.prototype.endsWith = function(suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
alert(str.endsWith("$"));
Run Code Online (Sandbox Code Playgroud)
ES5 没有endsWith函数(或者就此而言,startsWith)。您可以推出自己的版本,例如MDN中的这个版本:
if (!String.prototype.endsWith) {
Object.defineProperty(String.prototype, 'endsWith', {
enumerable: false,
configurable: false,
writable: false,
value: function (searchString, position) {
position = position || this.length;
position = position - searchString.length;
var lastIndex = this.lastIndexOf(searchString);
return lastIndex !== -1 && lastIndex === position;
}
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9149 次 |
| 最近记录: |