Working with JavaScript Strings: Finding a Substring in a String 5/12

Working with JavaScript Strings: Finding a Substring in a String 5/12

Problem

You want to find out if a substring, a particular series of characters, exists in a string.



Solution

Use the String object’s built-in indexOf method to find the position of the substring, if it exists:

var testValue = "This is the Cookbook's test string";
var subsValue = "Cookbook";
var iValue = testValue.indexOf(subsValue); // returns value of 12, index of substringif (iValue != -1) // succeeds, because substring exists


Discussion

The String indexOf method returns a number representing the index, or position of the first character of the substring, with 0 being the index position of the first character in the string.

To test if the substring doesn’t exist, you can compare the returned value to –1, which is the value returned if the substring isn’t found:

if (iValue != -1) // true if substring found


The indexOf method takes two parameters: the substring, and an optional second pa-rameter, an index value of where to begin a search:

var tstString = "This apple is my apple";
var iValue = tstString.indexOf("apple", 10); // returns 17, index of second substring


The indexOf method works from left to right, but sometimes you might want to find the index of a substring by searching within the string from right to left. There’s another String method, lastIndexOf, which returns the index position of the last occurrence of a substring within a string:

var txtString = "This apple is my apple";
var iValue = tstString.lastIndexOf("apple"); // returns 17,
                                             // index of last occurrence of substring


Like indexOf, lastIndexOf also takes an optional second parameter, which is an index value of where to start the search, counted from the right:

"This apple is my apple".lastIndexOf("apple"); // returns value of 17
"This apple is my apple".lastIndexOf("apple",12); // returns value of 5
"This apple is my apple".lastIndexOf("apple", 3); // returns value of -1, not found


Notice that the value returned from lastIndexOf changes based on the starting position,as counted from the string’s right.

It’s odd to see a String method called directly on quoted text, but in JavaScript, there’s no difference in calling the method on a string literal,directly, or on a string variable.

Comments

Popular posts from this blog

Working with JavaScript Strings: Conditionally Comparing Strings 4/12

Working with JavaScript Strings: Concatenating Two or More Strings 2/12