Check if a string contains another string as a substring in JavaScript
This post will discuss how to check whether a string contains another string as its substring in JavaScript.
1. Using String.prototype.includes() function
The includes() method can be used to check whether a given string includes another string or not. It returns true if the search string is found within the given string; false otherwise. Here’s how the code would look like:
|
1 2 3 4 |
var source = 'Hello World'; var target = 'llo'; console.log(source.includes(target)); |
This method has been introduced with the ES6 and may not be available in all JavaScript implementations yet. However, MDN has a simple polyfill for this method:
|
1 2 3 4 5 6 7 8 9 10 11 |
if (!String.prototype.includes) { String.prototype.includes = function(search, start) { 'use strict'; if (search instanceof RegExp) { throw TypeError('first argument must not be a RegExp'); } if (start === undefined) { start = 0; } return this.indexOf(search, start) !== -1; }; } |
2. Using Lodash Library
If you are using lodash library, the _.includes method will be useful:
|
1 2 3 4 5 6 |
var _ = require("lodash"); var source = 'Hello World'; var target = 'llo'; console.log(_.includes(source, target)); |
3. Using String.prototype.indexOf() function
The indexOf() method returns the index of the first occurrence of the target or -1 when the target string is not found. The following example demonstrates its usage.
|
1 2 3 4 |
var source = 'Hello World'; var target = 'llo'; console.log(source.indexOf(target) !== -1); |
4. Using String.prototype.search() function
Finally, you can also use the search() method to check if the source string contains the target string. The following example would return the index of the first match of the target in the given string, or -1 if it found no match.
|
1 2 3 4 |
var source = 'Hello World'; var target = 'llo'; console.log(source.search(target) !== -1); |
That’s all about determining whether a string contains another string as a substring in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)