Parse a string using JavaScript

Monday, February 19th, 2007 by Chris Jason
4 Comments

A handy trick for Web Developers in the ability to parse a string to check for a given substring. In plain English, this means checking if a word or part of a word is contained within text. This tutorial demonstrates how to do this using JavaScript.

Using the indexOf method in JavaScript

The indexOf method is the basis for parsing a string in JavaScript. It returns the position number of a given letter or word in a string.

Let’s say we have the word "cat," and we want to find out what position the letter "a" is. We know in advance that the answer is 2, or the second position. We could use the following code to determine this programmatically:

<script type="text/javascript">
var text = "cat";
aPosition = text.indexOf("a");
alert(aPosition); // Will display an alert box with the number 1
</script>

The reason this returns 1 is that JavaScript sees the text variable as an array of letters, and arrays generally start at 0. In actuality, "a" is the second letter in the word "cat," which we know is correct.

How to use indexOf to parse a string

Now that we know what the indexOf method does, how can we use it to parse a string? The answer is simple. If indexOf returns the position number of the letter/substring we are searching for, it will return -1 if no match is found. With a simple if/then conditional statement, we can determine if a string contains a substring.

<script type="text/javascript">
var text = "cats make great pets for the home";
if (text.indexOf("pet") > -1) {
alert("We have a match!")
}
else {
alert("No match found.")
}
</script>

Applying JavaScript string parsing to real projects

This basic code is the building block for much more complex Web applications that use JavaScript. A perfect example is hiding/showing DIVs. Others include form validations, client-side search engines, and more.

Article Comments

  • Posted by: Todd | July 10th, 2007

    JavaScript’s indexOf method returns -1 if no match is found, not 0 like stated. Just wanted to let you know since this was the top Google hit for my search.

  • Posted by: Christopher Jason | July 10th, 2007

    Thanks Todd for catching the typo. I’ve corrected the article.

  • Posted by: Norman | September 21st, 2007

    var text = “cat”;
    aPosition = text.indexOf(“cat”);

    This actually returns a value of 0, because the variable text contains only a single string. If the variable text was an array…

    var text=new Array();
    text[text.length]=”cat”;

    Then the variable text wouldd be “cat”, but text.length would be 1.

  • Posted by: Christopher Jason | September 23rd, 2007

    Haha thanks Norman for spotting another typo. In my example, I meant to set aPosition=text.indexOf(“a”), not “cat” as I mistakenly typed. I’ve corrected the example. I really needs to stop writing these late at night.

Post a Comment

You must be logged in to post a comment.