endsWith in JavaScript

前端 未结 30 958
-上瘾入骨i
-上瘾入骨i 2020-11-22 05:41

How can I check if a string ends with a particular character in JavaScript?

Example: I have a string

var str = \"mystring#\";

I wa

相关标签:
30条回答
  • 2020-11-22 06:16
    /#$/.test(str)
    

    will work on all browsers, doesn't require monkey patching String, and doesn't require scanning the entire string as lastIndexOf does when there is no match.

    If you want to match a constant string that might contain regular expression special characters, such as '$', then you can use the following:

    function makeSuffixRegExp(suffix, caseInsensitive) {
      return new RegExp(
          String(suffix).replace(/[$%()*+.?\[\\\]{|}]/g, "\\$&") + "$",
          caseInsensitive ? "i" : "");
    }
    

    and then you can use it like this

    makeSuffixRegExp("a[complicated]*suffix*").test(str)
    
    0 讨论(0)
  • 2020-11-22 06:17

    UPDATE (Nov 24th, 2015):

    This answer is originally posted in the year 2010 (SIX years back.) so please take note of these insightful comments:

    • Shauna - Update for Googlers - Looks like ECMA6 adds this function. The MDN article also shows a polyfill. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith

    • T.J. Crowder - Creating substrings isn't expensive on modern browsers; it may well have been in 2010 when this answer was posted. These days, the simple this.substr(-suffix.length) === suffix approach is fastest on Chrome, the same on IE11 as indexOf, and only 4% slower (fergetaboutit territory) on Firefox: jsperf.com/endswith-stackoverflow/14 And faster across the board when the result is false: jsperf.com/endswith-stackoverflow-when-false Of course, with ES6 adding endsWith, the point is moot. :-)


    ORIGINAL ANSWER:

    I know this is a year old question... but I need this too and I need it to work cross-browser so... combining everyone's answer and comments and simplifying it a bit:

    String.prototype.endsWith = function(suffix) {
        return this.indexOf(suffix, this.length - suffix.length) !== -1;
    };
    
    • Doesn't create a substring
    • Uses native indexOf function for fastest results
    • Skip unnecessary comparisons using the second parameter of indexOf to skip ahead
    • Works in Internet Explorer
    • NO Regex complications

    Also, if you don't like stuffing things in native data structure's prototypes, here's a standalone version:

    function endsWith(str, suffix) {
        return str.indexOf(suffix, str.length - suffix.length) !== -1;
    }
    

    EDIT: As noted by @hamish in the comments, if you want to err on the safe side and check if an implementation has already been provided, you can just adds a typeof check like so:

    if (typeof String.prototype.endsWith !== 'function') {
        String.prototype.endsWith = function(suffix) {
            return this.indexOf(suffix, this.length - suffix.length) !== -1;
        };
    }
    
    0 讨论(0)
  • 2020-11-22 06:17

    I just learned about this string library:

    http://stringjs.com/

    Include the js file and then use the S variable like this:

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

    It can also be used in NodeJS by installing it:

    npm install string
    

    Then requiring it as the S variable:

    var S = require('string');
    

    The web page also has links to alternate string libraries, if this one doesn't take your fancy.

    0 讨论(0)
  • 2020-11-22 06:19

    Come on, this is the correct endsWith implementation:

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

    using lastIndexOf just creates unnecessary CPU loops if there is no match.

    0 讨论(0)
  • 2020-11-22 06:20

    I don't know about you, but:

    var s = "mystring#";
    s.length >= 1 && s[s.length - 1] == '#'; // will do the thing!
    

    Why regular expressions? Why messing with the prototype? substr? c'mon...

    0 讨论(0)
  • 2020-11-22 06:20
    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)/));
    
    0 讨论(0)
提交回复
热议问题