Friday, March 13, 2020

JavaScript examples- 3 ways of Check subString contains in a string.

How to check substring exists in a given string in Javascript

check substring exists in a given string in Javascript

String checking operations is a basic operation every developer needs to know.
In this blog post, I will take you through several ways of checking substring exists in a given string in JavaScript.

  • ES5 String indexOf() method
  • Inbuilt String search() method
  • Using ES6 String includes() method

ES5 String indexOf method 

Prior to ES6, indexOf method used to check substring presence in main string. This returns -1 if string not found, else positional index of first occurrence of a given sub string.
Syntax
String.indexOf(substring)
Input and return values

  • input is given substring to check presence
  • returns number -1 or greater than 0. 

Example
let mainString = "String checking indexOf example";
console.log(mainString.indexOf("checking")) // 7
console.log(mainString.indexOf("asdfad")) // -1
Lets see one more example in conditional if expression
if(("first string".indexOf('string')==-1)){
console.log('not found');
}
else{
console.log('found');
}
From the above example, code looks not human readable, and if conditional expression always needs extra check against integer instead of simple truth or false values. So check integer values in if conditional expression is disadvantages.

String Search with regular expression 

This is one more way of checking string exists or not. This checks the regular expression against given string object and returns positional index, else not found, returns -1.
Syntax
String.search(reguar expression)
return type is index of matched starting position.
input accepted is regular expression.
let string = "search string example";
console.log(string.search('string') !== -1); // true
console.log(string.search('string') !== -1); // true
console.log(string.search('string')) // outputs 7
The disadvantages is regular expressions processing takes more time and resources, It is not advisable to use this for simple use cases.

ES6 String includes method 

 ES6 is new JavaScript features introduced in 2015 year. String has includes() new method which returns true if a given substring contains in a string Syntax
String.includes(substring,index)
Parameters

  • sub string - This is string text which checks for exists in a given string 
  • index - starting position at which checking starts from, and optional 
  • Returns true - if substring found false - not found in a given string Here is an examples

const message = "Substring checking example";

console.log(message.includes("example")); // true
console.log(message.includes("aserwerew")); // false
console.log(message.includes("as", 8)); // false
console.log(message.includes("string", 3)); // true

Related article


EmoticonEmoticon