Endswith in JavaScript
To verify if a str
ends with a specific substring, use the str.endsWith(substring)
ES6 function:
Pre-ES6 survival guide
Not everyone lives in an ES6 world. Older JavaScript versions may lack support for endsWith
. In such scenarios, a typeof
implementation check before using endsWith
can prevent surprises:
Diving deeper: Beyond basics
Regex to the rescue: endsWith alternative
If you can't use endsWith
or must handle complex patterns, regular expressions are your friends:
Performance matters: Substring methods vs charAt
Whilst it's tempting to use substr
and slice
methods, they could incur overhead by creating unnecessary substrings. In contrast, char comparison using string length avoids this overhead:
DIY: Custom endsWith
Sometimes built-in functions can't satisfy your needs. Crafting a customized endsWith
function, packaged as a standalone function, might be your solution—and it won't meddle with native prototypes:
Case sensitivity and regex
By default, regular expressions are case-sensitive. For case-insensitive endsWith
, use the i
flag:
Exploring the edges and corners
Age is just a number: Handling environments sans ES6
If you have to deal with legacy environments or outdated browsers that lack endsWith
, you can either use polyfills – MDN provides handy ones – or you can craft functions that simulate endsWith
:
Speed is the game: Performance-critical applications
For apps dealing with sizable strings or requiring responsive interactions, direct character comparison can deliver results faster than the substring approach:
I've got multiple choices: Dealing with multiple endings
For scenarios where you might need to check against a multitude of possible endings, a custom function accepting an array of endings simplifies things:
Was this article helpful?