There are several methods you can use to find substrings in JavaScript:
indexOf(): Returns the index of the first occurrence of the specified substring within a string, or -1 if the substring is not found.
let str = "Hello world";
let substr = "world";
let index = str.indexOf(substr);
console.log(index); // Output: 6
lastIndexOf(): Returns the index of the last occurrence of the specified substring within a string, or -1 if the substring is not found.
let str = "Hello world";
let substr = "l";
let index = str.lastIndexOf(substr);
console.log(index); // Output: 9
search(): Searches for a specified substring within a string and returns the position of the match, or -1 if the substring is not found.
let str = "Hello world";
let substr = "world";
let index = str.search(substr);
console.log(index); // Output: 6
includes(): Determines whether a string contains the specified substring and returns true or false.
let str = "Hello world";
let substr = "world";
let found = str.includes(substr);
console.log(found); // Output: true
startsWith(): Determines whether a string begins with the specified substring and returns true or false.
let str = "Hello world";
let substr = "Hello";
let found = str.startsWith(substr);
console.log(found); // Output: true
endsWith(): Determines whether a string ends with the specified substring and returns true or false.
let str = "Hello world";
let substr = "world";
let found = str.endsWith(substr);
console.log(found); // Output: true
Note that all these methods are case-sensitive. If you want to perform a case-insensitive search, you can convert both the string and the substring to lowercase or uppercase before performing the search.
Repeating string
output
String Padding
Top comments (0)