Primitive values, like "John Doe", cannot have properties or methods (because they are not objects).
But with JavaScript, methods and properties are also available to primitive values, because JavaScript treats primitive values as objects when executing methods and properties.
String Length
The length
property returns the length of a string:
Example
var sln = txt.length;
Finding a String in a String
The indexOf()
method returns the index of (the position of) the first
occurrence of a specified text in a string:
Example
var pos = str.indexOf("locate");
JavaScript counts positions from zero.
0 is the first position in a string, 1 is the second, 2 is the third ...
The lastIndexOf()
method returns the index of the last occurrence of a specified text in a string:
Example
var pos = str.lastIndexOf("locate");
Both indexOf()
, and lastIndexOf()
return -1 if the text is not found.
Example
var pos = str.lastIndexOf("John");
Both methods accept a second parameter as the starting position for the search:
Example
var pos = str.indexOf("locate", 15);
The lastIndexOf()
methods searches backwards (from the end to the beginning), meaning: if the second parameter is 15
, the search starts at position 15, and searches to the beginning of the string.
Example
var pos = str.lastIndexOf("locate", 15);
Practice Excercise Practice now