Languages
[Edit]
EN

JavaScript - String indexOf() method example

0 points
Created by:
Adnaan-Robin
724
// ONLINE-RUNNER:browser;

const text = 'ABCABC';

console.log(text.indexOf('A')); // 0
console.log(text.indexOf('B')); // 1
console.log(text.indexOf('C')); // 2

console.log(text.indexOf('A', 3)); // 3
console.log(text.indexOf('B', 3)); // 4
console.log(text.indexOf('C', 3)); // 5

console.log(text.indexOf('BC'));    // 1
console.log(text.indexOf('BC', 3)); // 4

console.log(text.indexOf('123'));    // -1
console.log(text.indexOf('123', 2)); // -1

1. Documentation

Syntax

String indexOf(searchString)

String indexOf(searchString, position)

Parameters

searchString - a substring to search for.

position - a position to search from.

Result

The method returns the index of the first occurrence of searchString or -1 if not found.

If the method is called with no arguments returns 0.

Description

The method searches the entire calling string and returns the index of the first occurrence of the specified substring.

If the second argument is given, the method returns the first occurrence of the specified substring at an index greater than or equal to the specified number.

See also

  1. JavaScript - get index of item in array

  2. JavaScript - index of text in string after indicated position

References

  1. String.prototype.indexOf() - JavaScript | MDN

Alternative titles

  1. JavaScript - String.indexOf() documentation with examples
  2. js - String indexOf() method documentation with examples
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

JavaScript - String (documentation)

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join