JavaScript中的endsWith

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

示例:我有一个字符串

var str = "mystring#";

我想知道该字符串是否以结尾#我该如何检查?

  1. endsWith()JavaScript中是否有方法?

  2. 我有一个解决方案是获取字符串的长度并获取最后一个字符并进行检查。

这是最好的方法还是还有其他方法?

番长前端2020/03/10 00:47:17

For coffeescript

String::endsWith = (suffix) ->
  -1 != @indexOf suffix, @length - suffix.length
小宇宙米亚猿2020/03/10 00:47:17

all of them are very useful examples. Adding String.prototype.endsWith = function(str) will help us to simply call the method to check if our string ends with it or not, well regexp will also do it.

I found a better solution than mine. Thanks every one.

古一番长小小2020/03/10 00:47:17

Do not use regular expressions. They are slow even in fast languages. Just write a function that checks the end of a string. This library has nice examples: groundjs/util.js. Be careful adding a function to String.prototype. This code has nice examples of how to do it: groundjs/prototype.js In general, this is a nice language-level library: groundjs You can also take a look at lodash

斯丁宝儿2020/03/10 00:47:17
if(typeof String.prototype.endsWith !== "function") {
    /**
     * String.prototype.endsWith
     * Check if given string locate at the end of current string
     * @param {string} substring substring to locate in the current string.
     * @param {number=} position end the endsWith check at that position
     * @return {boolean}
     *
     * @edition ECMA-262 6th Edition, 15.5.4.23
     */
    String.prototype.endsWith = function(substring, position) {
        substring = String(substring);

        var subLen = substring.length | 0;

        if( !subLen )return true;//Empty string

        var strLen = this.length;

        if( position === void 0 )position = strLen;
        else position = position | 0;

        if( position < 1 )return false;

        var fromIndex = (strLen < position ? strLen : position) - subLen;

        return (fromIndex >= 0 || subLen === -fromIndex)
            && (
                position === 0
                // if position not at the and of the string, we can optimise search substring
                //  by checking first symbol of substring exists in search position in current string
                || this.charCodeAt(fromIndex) === substring.charCodeAt(0)//fast false
            )
            && this.indexOf(substring, fromIndex) === fromIndex
        ;
    };
}

Benefits:

  • This version is not just re-using indexOf.
  • Greatest performance on long strings. Here is a speed test http://jsperf.com/starts-ends-with/4
  • Fully compatible with ecmascript specification. It passes the tests
ItachiTom2020/03/10 00:47:17

This is the implementation of endsWith : String.prototype.endsWith = function (str) { return this.length >= str.length && this.substr(this.length - str.length) == str; }

ItachiTom2020/03/10 00:47:17

This is the implementation of endsWith :

String.prototype.endsWith = function (str) { return this.length >= str.length && this.substr(this.length - str.length) == str; }

凯卡卡西2020/03/10 00:47:17

After all those long tally of answers, i found this piece of code simple and easy to understand!

function end(str, target) {
  return str.substr(-target.length) == target;
}
米亚十三Harry2020/03/10 00:47:17
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)/));
年轻不拽世界怎么精彩2020/03/10 00:47:17

if you dont want to use lasIndexOf or substr then why not just look at the string in its natural state (ie. an array)

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

or as a standalone function

function strEndsWith(str,suffix) {
    if (str[str.length - 1] == suffix) return true;
    return false;
}
GilGreen2020/03/10 00:47:17
function check(str)
{
    var lastIndex = str.lastIndexOf('/');
    return (lastIndex != -1) && (lastIndex  == (str.length - 1));
}
小小逆天2020/03/10 00:47:17

另一个使用正则表达式的快速替代方法对我来说很有吸引力:

// Would be equivalent to:
// "Hello World!".endsWith("World!")
"Hello World!".match("World!$") != null
小宇宙古一2020/03/10 00:47:17
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;
}
Davaid阳光小卤蛋2020/03/10 00:47:16

来自developer.mozilla.org String.prototype.endsWith()

摘要

endsWith()方法确定一个字符串是否以另一个字符串的字符结尾,并根据需要返回true或false。

句法

str.endsWith(searchString [, position]);

参量

  • searchString:在此字符串末尾要搜索的字符。

  • position:在此字符串中搜索,就好像该字符串只有这么长;默认为该字符串的实际长度,限制在该字符串的长度所建立的范围内。

描述

此方法使您可以确定一个字符串是否以另一个字符串结尾。

例子

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

alert( str.endsWith("question.") );  // true
alert( str.endsWith("to be") );      // false
alert( str.endsWith("to be", 19) );  // true

技术指标

ECMAScript语言规范第六版(ECMA-262)

浏览器兼容性

浏览器兼容性

小胖GO2020/03/10 00:47:16

没有看到slice方法的配合。所以我就把它留在这里:

function endsWith(str, suffix) {
    return str.slice(-suffix.length) === suffix
}
神乐神无2020/03/10 00:47:16

此版本避免创建子字符串,并且不使用正则表达式(此处提供某些正则表达式答案;而其他则不适用):

String.prototype.endsWith = function(str)
{
    var lastIndex = this.lastIndexOf(str);
    return (lastIndex !== -1) && (lastIndex + str.length === this.length);
}

如果性能对您很重要,那么值得测试一下是否lastIndexOf实际上比创建子字符串更快。(这可能取决于您使用的JS引擎...)在匹配的情况下,它可能会更快,并且当字符串很小时-但是当字符串很大时,甚至需要回顾整个过程虽然我们并不在乎:(

对于检查单个字符,找到长度然后使用charAt可能是最好的方法。

Davaid米亚2020/03/10 00:47:16
  1. 不幸的是没有。
  2. if( "mystring#".substr(-1) === "#" ) {}
村村阿飞2020/03/10 00:47:16

拜托,这是正确的endsWith实现:

String.prototype.endsWith = function (s) {
  return this.length >= s.length && this.substr(this.length - s.length) == s;
}

lastIndexOf如果不匹配,使用只会创建不必要的CPU循环。

乐米亚2020/03/10 00:47:16
return this.lastIndexOf(str) + str.length == this.length;

在原始字符串的长度比搜索字符串的长度小一且找不到搜索字符串的情况下不起作用:

lastIndexOf返回-1,然后添加搜索字符串的长度,然后剩下原始字符串的长度。

可能的解决方法是

return this.length >= str.length && this.lastIndexOf(str) + str.length == this.length