javascript indexof – How to Use the indexOf method in JavaScript?

javascript indexof – The indexOf() method is a part of the Array prototype and the String prototype, and therefore it applies to objects of both types.

Free Live Chat for Any Issue

let index = str.indexOf(substr, [, fromIndex]);

javascript indexof – JavaScript String indexOf()

let userInput = "Greeting Message, Pakainfo to the best Website.";
userInput.indexOf("Pakainfo") 
userInput.indexOf("Pakainfo")   

1) Using indexOf() method example

let userInput = 'finding substring in string';
let index = userInput.indexOf('str');

console.log(index);

2) Using indexOf() to count occurrences of a substring in a string

let userInput = 'Stripe Payment Gateway Integration using PHP';
let subuserInput = 'Gateway';

let count = 0;

let index = userInput.indexOf(subuserInput);
while(index !== -1) {
    count++;
    index = userInput.indexOf(subuserInput, index + 1);
}

console.log(count);

3) The indexOf() and case-sensitivity

let userInput = 'Free Download Gateway indexOf';
let results = 'Gateway';

let index = userInput.indexOf(results);

console.log(index);

Example

let userInput = 'Free Download Gateway indexOf';
let results = 'Gateway';

let index = userInput.toLocaleLowerCase().indexOf(results.toLocaleLowerCase());

console.log(index);

Don’t Miss : JavaScript InArray Check If Value Exists

I hope you get an idea about javascript indexof.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, donโ€™t forget to share.