Substituting Substring's Integer Parameters With indexOf()

Enter your name.

Since we will not always have the luxury of knowing the exact value of a string, we cannot rely on using integers as substring parameters to extract a new string. Luckily, the substring method's parameters can be an expression representing an integer. This opens the door to using indexOf and lastIndexOf expressions in place of specific index positions.
var stringName = "Billy Bob Zeek"

stringName.substring(0, stringName.indexOf(" "))

// result is character 0 through the first instance of a space, or "Billy"
If the ending point of your substring is the end of the string, you can use the length property.
var stringName = "Billy Bob Zeek"

stringName.substring(stringName.lastIndexOf(" "), stringName.length)

// result is last instance of a space through the length or end of the string, "Zeek"
The first and last names are fairly easy to extract because we have the luxury of an exact starting point for the first name (0), and the exact ending point of the last name (length). The middle name takes a bit more work because we don't know the index of either the starting or ending points.
var stringName = "Billy Bob Zeek"

stringName.substring(stringName.indexOf(" ")+1, stringName.lastIndexOf(" "))

// result is first instance of a space plus 1 (don't want to include the space) through the last instance of a space, "Bob"
These examples work great if we are working with strings that have absolutes, such as the URL. However, these examples assume the user has entered the string correctly, and we know by now that you can never make that assumption. For instance, what if the user entered a space at the beginning or end of their name, or more than one space between the 3 names?

View the Source


View Source | Home | Contact