JavaScript Solutions, Competitive programming in JavaScript, MCQ in JS

Sunday, 15 December 2019

JavaScript check string contains in string or not using search() method

JS find string contains in string

If you want to check whether substring present or not in javascript then following are methods you can use:

JavaScript Search() method to check whether the string contains substring is there or not


const str = "this is main string to check";
const subStr = "main string";
if (str.search(subStr)) {
console.log(`${subStr} string is present in ${str}`);
} else {
console.log(`${subStr} string is not present in ${str}`);
}

The Output will be as follows:

JavaScript check string contains in string or not


Definition of Search() method


  • The search() method searches a string for a specified value and returns the position of the match.
  • Search()  method returns -1 if no match is found.
  • We can search on a string or on a regular expression.
  • It will return the first occurrence of the specified value.


I will post more method in upcoming posts which I will link over there so you can check it.

Thanks.


No comments:

Post a Comment