5

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

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

上面简单的 JS 代码根本不起作用?

4

4 回答 4

8

正如这篇文章所说的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

编辑

在这里检查之前有一个类似的问题

答案说

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("$"));
于 2013-09-12T15:39:33.793 回答
3

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;
        }
    });
}
于 2013-09-12T15:32:22.737 回答
0

我从未见过endsWithJS 中的函数。您可以执行 String.length,然后通过手动引用要检查的每个字符来检查最后一个单词。

更好的是做一个正则表达式来查找字符串中的最后一个单词,然后使用它(正则表达式来查找句子中的最后一个单词)。

于 2013-09-12T15:35:12.577 回答
0

我发现endsWith()Chrome 控制台中可用的功能,但奇怪的是,在 VS Code(使用 Chrome)中调试时没有定义。您可以尝试通过删除 polyfill 来编辑下面的代码段,以查看您的浏览器是否支持它。

这是来自MDN 开发人员文档String.prototype.endsWith()的引用:

String.prototype.endsWith()

此方法已添加到 ECMAScript 6 规范中,可能尚未在所有 JavaScript 实现中可用。但是,您可以使用以下代码段 polyfill String.prototype.endsWith():

// If string.endsWith() isn't defined, Polyfill it.
if (!String.prototype.endsWith) {
  String.prototype.endsWith = function(search, this_len) {
    if (this_len === undefined || this_len > this.length) {
      this_len = this.length;
    }
    return this.substring(this_len - search.length, this_len) === search;
  };
}

// Use it.
const myString = "Mayberry";
const result = myString.endsWith("berry") ? 'Yes' : 'Nope';
document.body.append('A. ' + result);
Q. Does Mayberry end with "berry"?<br>

于 2020-12-04T00:20:09.880 回答