Checking for Substrings in Javascript - ES6 Methods

javascript
Published on January 20, 2019

ES6 has brought forward newer ways of checking for substrings. The best part is that they all return either a true or false — unlike the usual indexOf method.

Checking Anywhere in the String with includes

  • includes checks for a substring in a given string
  • Returns a boolean true if the search string is found anywhere in the given string, false otherwise
  • includes is case sensitive
var main_string = 'Hello what are you looking for ?';
var search = 'looking';

// gives true
console.log(main_string.includes(search));

Checking in the Starting of String with startsWith

  • startsWith checks whether a string starts with a given substring
  • Returns true if substring is found in the beginning of the string, false otherwise
  • case sensitive
var main_string = 'Twinkle twinkle little star';

// gives true
console.log(main_string.startsWith('Twinkle'));

// gives false
console.log(main_string.startsWith('little'));

Checking in the Ending of String with endsWith

  • endsWith checks whether a string ends with a given substring
  • Returns true if substring is found in the end of the string, false otherwise
  • case sensitive
var main_string = 'My name is James Bond';

// gives true
console.log(main_string.endsWith('Bond'));

// gives false
console.log(main_string.endsWith('James'));

Checking for Case Insensitive Substrings ?

All the 3 methods discussed above are case sensitive. For a case-insensitive search you can use toLowerCase method to convert both the main string and search sting to lowercase and then use the usual includes, startsWith or endsWith.

main_string.toLowerCase().includes(search.toLowerCase())

Otherwise you will need to perform a search with regular expressions using search or test methods.

In this Tutorial