JavaScript Glossary: String indexOf()

Publikováno: 25.3.2019

Basics

This method checks for the first appearance of a provided string argument within the calling string and returns the index. It returns -1 if the string argument can’t be...

Celý článek

Basics

This method checks for the first appearance of a provided string argument within the calling string and returns the index. It returns -1 if the string argument can’t be found within the calling String.

"Hello and welcome to the scotch.io glossary, the end".indexOf("the")
// 21

https://scotch.io/embed/gist/38d235b6bdd4aaefd178107087f8ad4f

The indexOf() method:

  • Takes a string argument
  • Checks if the provided argument exists within the calling string object
  • Returns the index of the first appearance of the provided argument, -1 if it can’t be found.

Syntax

const indexOfWord = string.indexOf(searchParam, startIndex)

2 Parameters

searchParam This is the parameter to search for within the string - required

startIndex This is the index at which the search will begin. Search typically begins from the arr.length - 1 index, which is the last position in the string. If the value provided is less that 0, the string will not be searched.

Returns a number

This method returns a number which is the index of the first occurence of the searched string.

The indexOf() method is case sensitive

Common Uses and Snippets

Verify the first word in a sentence

The .indexOf() method is commonly used to verify the first occurence and position of a word in a sentence.

https://scotch.io/embed/gist/5fa053f1407eea649819528cd744d5c8

Nahoru
Tento web používá k poskytování služeb a analýze návštěvnosti soubory cookie. Používáním tohoto webu s tímto souhlasíte. Další informace