Game Lab Documentation

[string].indexOf(searchValue)

Category:Variables

In apps you sometimes need to check if one string is contained in another string, and if so, where. For example, to split comma delimited 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

Example: question?

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

Example: case sensitive

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 the fields

Parse a comma-delimited 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

NameTypeRequired?Description
stringstring

The string to search.

searchValuestring

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 support@code.org.