gpt4 book ai didi

JavaScript endsWith 函数不起作用

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:25:18 25 4
gpt4 key购买 nike

我有一个网络应用程序。在其中一个页面中,我遍历了所有 HTML 元素 ID,无论其中一个是否以指定的字符串结尾。每个 JS 函数都在页面上工作,但“endsWith”函数不起作用。我真的不明白这件事。谁能帮忙?

var str = "To be, or not to be, that is the question.";
alert(str.endsWith("question."));

上面简单的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."));

如果它以提供的后缀结尾,这将返回 true。

JSFIDDLE

编辑

在检查之前有一个类似的问题被问到here

答案是

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("$"));

关于JavaScript endsWith 函数不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18768344/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com