JavaScript endsWith函数不起作用

时间:2013-09-12 15:25:35

标签: javascript

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

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

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

4 个答案:

答案 0 :(得分:5)

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

答案 1 :(得分: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;
        }
    });
}

答案 2 :(得分:0)

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

更好的方法是使用正则表达式来查找字符串中的最后一个单词,然后使用它(Regular expression to find last word in sentence)。

答案 3 :(得分:0)

我发现endsWith()函数在Chrome控制台中可用,但是奇怪的是,在VS Code(带有Chrome)中进行调试时未定义。您可以尝试删除下面的代码段,以编辑以下代码段,以查看您的浏览器是否支持该代码段。

这是来自MDN Developer Docs for String.prototype.endsWith()的引文:

String.prototype.endsWith()

此方法已添加到ECMAScript 6规范中,并且可能 并非在所有JavaScript实现中都可用。但是你 可以用以下代码片段填充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>