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

示例:我有一个字符串

var str = "mystring#";

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

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

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


当前回答

如果你不想使用lasIndexOf或substr,那么为什么不只是看看字符串在它的自然状态(即。一个数组)

String.prototype.endsWith = function(suffix) {
    if (this[this.length - 1] == suffix) return true;
    return false;
}

或者作为一个独立的函数

function strEndsWith(str,suffix) {
    if (str[str.length - 1] == suffix) return true;
    return false;
}

其他回答

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)/));

对于coffeescript

String::endsWith = (suffix) ->
  -1 != @indexOf suffix, @length - suffix.length
String.prototype.endsWith = function(str) 
{return (this.match(str+"$")==str)}

String.prototype.startsWith = function(str) 
{return (this.match("^"+str)==str)}

我希望这对你们有帮助

var myStr = “  Earth is a beautiful planet  ”;
var myStr2 = myStr.trim();  
//==“Earth is a beautiful planet”;

if (myStr2.startsWith(“Earth”)) // returns TRUE

if (myStr2.endsWith(“planet”)) // returns TRUE

if (myStr.startsWith(“Earth”)) 
// returns FALSE due to the leading spaces…

if (myStr.endsWith(“planet”)) 
// returns FALSE due to trailing spaces…

传统的方式

function strStartsWith(str, prefix) {
    return str.indexOf(prefix) === 0;
}

function strEndsWith(str, suffix) {
    return str.match(suffix+"$")==suffix;
}

如果你不想使用lasIndexOf或substr,那么为什么不只是看看字符串在它的自然状态(即。一个数组)

String.prototype.endsWith = function(suffix) {
    if (this[this.length - 1] == suffix) return true;
    return false;
}

或者作为一个独立的函数

function strEndsWith(str,suffix) {
    if (str[str.length - 1] == suffix) return true;
    return false;
}
function strEndsWith(str,suffix) {
  var reguex= new RegExp(suffix+'$');

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

  return false;
}