indexOf

Category:Variables

[string].indexOf(searchValue)

Category: Variables

Returns the position of the first occurrence of searchValue within the string, else returns -1 if not found.

In apps you sometimes need to check if one string is contained in another string, and if so, where. For example, to split comma delimted data into individual data fields. indexOf() returns a the numeric position where the searchString was first found in the string, else it returns -1 if =not found. To call the indexOf function you need use a variable containing a string, followed by a dot ("."), followed by the function name "indexof()" with a string argument or variable of what to search for.

Examples


// See if a sentence is a question or not.
var sentence="How old are you?";
console.log(sentence.indexOf("?") == (sentence.length-1));

Example: Original Gettysburg Address Demonstrate that indexOf() is case sensitive.

// Demonstrate that indexOf is case sensitive.
var gettysburgAddress="Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal.";
console.log(gettysburgAddress.indexOf("Four"));
console.log(gettysburgAddress.indexOf("four"));

Example: Parse Comma-Delimited Data Parse a comma-delimted string into fields.

// Parse a comma-delimted string into fields.
var data="Titantic,1997,James Cameron,PG-13";
var commaPosition=data.indexOf(",");
while (commaPosition!=-1) {
  console.log(data.substring(0,commaPosition));
  data=data.substring(commaPosition+1,data.length);
  commaPosition=data.indexOf(",");
}
console.log(data);

Syntax

[string].indexOf(searchValue)

Parameters

Name Type Required? Description
string string Yes The string to search.
searchValue string Yes The string to search for.

Returns

Returns the position of the first occurrence of searchValue within the string, else returns -1 if not found.

Tips

  • The search is a case-sensitive search.

Found a bug in the documentation? Let us know at documentation@code.org

Found a bug in the documentation? Let us know at documentation@code.org