Ignore case of startsWith, endsWith Methods in JavaScript

avatar

Borislav Hadzhiev

Mon Oct 04 20211 min read

Ignore case of startsWith, endsWith Methods in JavaScript #

To ignore the case when using the startsWith method, convert the entire string and the substring to lowercase when calling the method.

index.js
// Not Supported in IE 6-11 const str = 'Hello world'; const substr = 'HELL'; // ๐Ÿ‘‡๏ธ true console.log(str.toLowerCase().startsWith(substr.toLowerCase())); if (str.toLowerCase().startsWith(substr.toLowerCase())) { // ๐Ÿ‘‰๏ธ string starts with substring }

In the code snippet, we called the String.startsWith method with two lowercase strings.

You could achieve the same result by converting the strings to uppercase.

As long as both strings are the same case, we can do a case insensitive check, whether the string starts with the specified substring.

Note that the String.startsWith method is not supported in Internet Explorer 6-11. If you have to support the browser, you have to polyfill the method or use babel to transpile your code to an older version of JavaScript.

To ignore the case when using the endsWith method, convert the entire string and the substring to lowercase when calling the method.

index.js
// Not Supported in IE 6-11 const str = 'Hello world'; const substr = 'ORLD'; // ๐Ÿ‘‡๏ธ true console.log(str.toLowerCase().endsWith(substr.toLowerCase())); if (str.toLowerCase().endsWith(substr.toLowerCase())) { // ๐Ÿ‘‰๏ธ string ends with substring }

Same as with startsWith, we convert the string and substring to lowercase to perform the case insensitive check, whether the strings ends with the substring.

The String.endsWith method is also not supported in IE 6-11.

If you have to support any of the versions of Internet Explorer, it's best to use a polyfill or babel to compile your code to a version of JavaScript the browser can understand.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee