AppDividend
Latest Code Tutorials

Javascript String Includes Example | String.prototype.includes() Tutorial

0

Javascript String Includes Example | String.prototype.includes() Tutorial is today’s topic. The string includes() method determines whether one string may be found within another string, returning true or false as appropriate. With ES6 JavaScript added the includes method natively to both the Array and String natives. While true or false may provide the answer you need, regular expressions can check if a sub-string exists with a more detailed answer.

Javascript String Includes Example

The string includes() method lets you determine whether or not a string includes another string. See the following syntax.

str.includes(searchString)

It has only one required parameter which is searchString. It is the substring, which we need to search in the String. See the following example.

// app.js

strA = 'Hello World, Welcome to ES9';

console.log(strA.includes('ES9'));

 In the above example, we are checking if the ES9 substring is there inside the strA and if yes then it will return true. In the above example, it is there, so we will see the output true.

 

Javascript String Includes Example

Javascript String Includes() method is case sensitive. For example, the following expression returns false.

See the below example.

// app.js

strA = 'Hello World, Welcome to ES9';

console.log(strA.includes('es9'));

The output of the above example is false because we have written the es9 in small letters.

 

String.prototype.includes() Tutorial

The string includes() method has been added to the ECMAScript 2015 specification and may not be available in all JavaScript implementations yet. However, you can easily polyfill this method.

if (!String.prototype.includes) {
  Object.defineProperty(String.prototype, 'includes', {
    value: function(search, start) {
      if (typeof start !== 'number') {
        start = 0
      }
      
      if (start + search.length > this.length) {
        return false
      } else {
        return this.indexOf(search, start) !== -1
      }
    }
  })
}

Finally, Javascript String Includes Example | String.prototype.includes() Tutorial is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.