Endswith in JavaScript

endsWith in JavaScript

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: https://jsben.ch/OJzlM 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;
};
}

How to test if string ends with a list of string

How about Array.prototype.some()?

if (strings.some(s => 'hi, this is a test'.endsWith(s))) {...}

How to use endsWith with multiple values?

I'd say regex is better here:

if (/[13579]$/.test(profileID)) {
// do what you need to do
}

JavaScript endsWith function not working

As said in this post 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."));

this will return true if it ends with provided suffix.

JSFIDDLE

EDIT

There is a similar question asked before check it here

the answer says

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

string.endswith( ) does not work in IE(not sure how to use a Polyfill)

The polyfill function you have is actually for attaching the endsWith function to the native String object, which JavaScript allows you to do. It will allow you to call endsWith like normal.

Instead of wrapping it in a function, let it run right away, then just use the normal endsWith:

if (!String.prototype.endsWith) {
String.prototype.endsWith = function (searchString, position) {
var subjectString = this.toString();
if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) {
position = subjectString.length;
}
position -= searchString.length;
var lastIndex = subjectString.lastIndexOf(searchString, position);
return lastIndex !== -1 && lastIndex === position;
}
}

Obj = JSON.parse(JSON.stringify(BubbleObj)).map(function (e) {
return Object.keys(e).reduce(function (p, n) {
if (n.endsWith("Value"))
p[n] = Math.round(e[n] * 100) / 100;
else
p[n] = e[n];
return p;
}, {})
});

Check if string ends with any of multiple characters

endsWith just doesn’t take multiple strings to test. You could define an array of them and check each value with endsWith:

function endsWithAny(suffixes, string) {
return suffixes.some(function (suffix) {
return string.endsWith(suffix);
});
}

function myFunction() {
var str = "Hello?";
var n = endsWithAny([".", "!", "?"], str);
document.getElementById("demo").innerHTML = n;
}

Or use a regular expression for a one-off:

var n = /[.!?]$/.test(str);


Related Topics



Leave a reply



Submit