Check If One String Contains Another Substring in JavaScript | Code Snippet #20

3 Feb , 2014  Code Snippets 

SubString-Comparison-JavaScript-Code-SnippetCode Snippet #20:  The code snippet teaches us to compare and check if one string contains another substring in JavaScript. Basically we are going to perform a string comparison using JavaScript.

Today, we are going to see how two string can be compared with the help of JavaScript using indexOf() method. indexOf() method returns the position of the first occurrence of a specified value in a string. If the search fails, it returns -1.

We will be using this logic of indexOf() method to check a string contains another sub-string. This code is simple and easy to understand. You can check the demo below followed by the code snippet.

Demo for two string comparison: (Enter the first main string in box 1 and sub-string to compare in the second box)




We create a form, where we take the strings to be compared as inputs. When the form is submitted, we call the function get(). Where we get the values of the input strings as “str” and “substr”.

We use an if look where we use the indexOf() function to compare the two strings not equal to -1, then it contains the substring from first string else it doesn’t.

Hope you enjoyed the snippet, if you have any doubts or suggestions please let us know by commenting below.




, ,

Comments are closed.