Debug School

rakesh kumar
rakesh kumar

Posted on

Finding Substring and Repeating string in Javascript

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

Image description

output

Image description

String Padding

Image description

Image description

Top comments (0)