Published on 2021-08-08, by Javed Shaikh
Sometimes when you are building an app in JavaScript, you may come across a situation where you would like to check if a string contains a substring or not. Thankfully we have inbuilt functions to do this job. There are two methods in JavaScript to find if a string contains another string or not such as includes() and indexOf() methods.
The includes() method returns true or false after a search and indexOf() method returns index of a string or -1 if it does not find a match.
Here we will learn about two such methods with examples and see how they work.
This method checks calling string and performs a scan to see if it contains the another string.This method returns either true or false. If a match is found, it returns true else it returns false. The search performed is case sensitive.
1const quote = “Heaven is under our feet as well as over our heads.”;
2const text = “feet”;
3
4console.log(quote.includes(text)) //true
5console.log(quote.includes("heaven")) //false due case sensitive search
6console.log(quote.includes("Heaven",15)) //false
7console.log(quote.includes("Heaven")) //true
8
9//below snippet prints "found a match"
10if(quote.includes("heads")){
11 console.log("found a match")
12}
13
14else{
15 console.log("not found")
16}
17
This method performs a search to check if a string contains another string and returns its index if a match is found. If it does not find a match then it returns -1. This method also does case sensitive search.
1const quote = "A weed is no more than a flower in disguise."
2
3console.log(quote.indexOf("weed")) //2
4console.log(quote.indexOf("weed",3)) //-1
5console.log(quote.indexOf("tree")) //-1
6console.log(quote.indexOf("flower")) //25
7console.log(quote.indexOf("Flower")) //-1
8console.log(quote.indexOf("disguise",25)) //35
World Wide Web Consortium or W3C introduced two storage object mechanisms to store data in the browser which are localStorage and sessionStorage objects
2021-07-28
The HTTP protocol is stateless which means that the server does not remember about any response it sent to the user’s browser. It executes each request independently without knowing past requests that are already executed.
2021-07-26
Instead of using any library function, in this post we are going to learn how to check if a string is null, blank, empty or undefined with just one line instruction
2021-08-10