如何检查字符串是否以JavaScript中的特定字符结束?

示例:我有一个字符串

var str = "mystring#";

我想知道字符串是否以#结尾。我怎么检查呢?

在JavaScript中有endsWith()方法吗? 我有一个解决方案,取字符串的长度,并得到最后一个字符,并检查它。

这是最好的办法还是还有别的办法?


当前回答

String.prototype.endWith = function (a) {
    var isExp = a.constructor.name === "RegExp",
    val = this;
    if (isExp === false) {
        a = escape(a);
        val = escape(val);
    } else
        a = a.toString().replace(/(^\/)|(\/$)/g, "");
    return eval("/" + a + "$/.test(val)");
}

// example
var str = "Hello";
alert(str.endWith("lo"));
alert(str.endWith(/l(o|a)/));

其他回答

我刚刚了解了这个字符串库:

http://stringjs.com/

包括js文件,然后像这样使用S变量:

S('hi there').endsWith('hi there')

它也可以通过安装在NodeJS中使用:

npm install string

然后需要它作为S变量:

var S = require('string');

这个网页还提供了其他字符串库的链接,如果你不喜欢这个库的话。

function strEndsWith(str,suffix) {
  var reguex= new RegExp(suffix+'$');

  if (str.match(reguex)!=null)
      return true;

  return false;
}

他们都是非常有用的例子。添加string .prototype. endswith = function(str)将帮助我们简单地调用该方法来检查字符串是否以它结尾,regexp也会这样做。

我找到了比我更好的解决办法。谢谢大家。

在所有这些长时间的答案之后,我发现这段代码简单易懂!

function end(str, target) {
  return str.substr(-target.length) == target;
}

这么多东西,这么小的问题,只是使用这个正则表达式

Var STR = "mystring#"; Var regex = /^.*#$/ 如果(regex.test (str)) { //如果后面有一个'#' }