AppDividend
Latest Code Tutorials

Javascript String indexOf: How to Get Index of String

The indexOf() method comes under two JavaScript data types.

  1. String indexOf()
  2. Array indexOf()

In this tutorial, we will learn about the JavaScript String indexOf() function and how we can use it in different cases.

Javascript String indexOf

The string indexOf() is a built-in JavaScript function that returns the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex. The string indexOf() function accepts searchvalue and start as arguments and returns -1 if the value is not found.

The characters in a string are indexed from left to right. The index of the first character is 0, and the last character of a string called stringName is stringName.length-1.

Syntax

string.indexOf(searchvalue, start)

Parameters

The searchValue is a required field. It is the String that we need to search for.

The start parameter is optional. The default is 0, at which position to start the search in a string.

Return Value

The indexOf returns the String index (0-based), where the searchValue is found first. If the searchValue cannot be found in the String, the function returns -1

The method checks each substring against searchValue using strict equality (===), which means this method is case-sensitive.

Example

// app.js

let str = 'Winter is coming';
let position = str.indexOf('coming');

console.log(position);

Javascript String indexOf Example | String.prototype.indexOf()

The indexOf method is case-sensitive. For example, the following expression returns -1.

// app.js

let str = 'Winter is coming';
let position = str.indexOf('winter');

console.log(position);

Here, we are looking for small-cap winter, which is not present in the String. So it will return to -1 position.

See another following example. We will count the appearances of a character in a string using the following code.

// app.js

const str = 'Winter is coming';
let count = 0;
let position = str.indexOf('i');

while (position !== -1) {
  count++;
  position = str.indexOf('i', position + 1);
}

console.log(count);

So, in the above code, we have provided one String, and we will count the i character appearing on that screen and printing on the console.

Javascript String indexOf Example

Using indexOf() to count occurrences of a letter in a string

To count occurrences of a letter in a string in JavaScript, use the string.indexOf() function. Let’s count the number of occurrences of the letter b in the String.

// app.js

const str = 'Millie Bobby Brown';
let count = 0;
let position = str.indexOf('b');

while (position !== -1) {
  count++;
  position = str.indexOf('b', position + 1);
}

console.log(count);

In the above example, we will count the occurrence of the character. However, the string indexOf() character is case-sensitive, so it will not count the character.

See the output.

➜  es git:(master) ✗ node app
2
➜  es git:(master) ✗

Javascript includes() vs. indexOf()

The difference between the includes() and indexOf() method is that the Javascript string includes() method determines whether one string may be found within another string, returning true or false as appropriate.

The indexOf() method returns an index within the calling String object of the first occurrence of a specified value, starting the search at fromIndex().

Javascript String indexOf with case insensitive

Let’s say I have a string that is like “Krunal,” and still, I want to match that String with “krunal”. We can use the JavaScript toLowerCase() function with indexOf() function.

See the following code with different strings and see the output.

// app.js

const str = 'Millie Bobby Brown';
if (str.toLowerCase().indexOf("millie bobby brown") === -1) { 
  console.log('Match Not found');
}
else {
  console.log('Match found')
}

See the output.

➜  es git:(master) ✗ node app
Match found
➜  es git:(master) ✗

String indexOf() function with regex

We can also use the Javascript regex to match the pattern. Let’s see the above example, and if we find the match, it will print the match found; otherwise, not.

// app.js

const str = 'Millie Bobby Brown';
if (!/millie/i.test(str)) {
  console.log('Match Not found');
}
else {
  console.log('Match found')
}

We have achieved using a Regular Expression, and it is beneficial when you want to test against dynamic patterns.

See the output.

➜  es git:(master) ✗ node app
Match Not found
➜  es git:(master) ✗

Difference between String indexOf() and search()

Javascript search() function takes the regular expression, which allows you to match against more sophisticated patterns, case-insensitive strings, etc. If you require the regular expression, use search(). Otherwise, indexOf() is going to be faster.

An indexOf() function matches the literal String. However, indexOf() also allows you to specify a beginning index.

Browser and Node Compatibility(Version and above)

  1. Google Chrome v1
  2. Internet Explorer v3
  3. Firefox v1
  4. Edge v12
  5. Opera  
  6. Safari v1
  7. Android webview v1 
  8. Chrome for Android v18
  9. Firefox for Android v4
  10. Opera for Android 
  11. Safari on iOS v1
  12. Samsung Internet v1.0
  13. Node.js

Conclusion

Javascript String indexOf() method returns an index within the calling String object of the first occurrence of a specified value, starting the search at fromIndex(). It returns -1 if the value is not found. The indexOf() method is case-sensitive.

If you want to find an index of the particular item in the array, use the Javascript array indexOf() method.

That is it for this tutorial.

Recommended Posts

Javascript String toLocaleUpperCase()

Javascript String toLocaleLowerCase()

Javascript String valueOf()

Javascript String lastIndexOf()

Javascript String charCodeAt()

Javascript String startsWith()

Javascript String trimStart() trimEnd()

Javascript String toUpperCase()

Javascript String toLowerCase()

Javascript String split()

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.