Ignore case of startsWith, endsWith Methods in JavaScript

avatar

Borislav Hadzhiev

Last updated: Oct 4, 2021

banner

Photo from Unsplash

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.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.