• Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

1. Strings > 1.5. Testing String Containment Without Regular Expressions

Testing String Containment Without Regular Expressions

NN 2, IE 3

Problem

You want to know if one string contains another, without using regular expressions.

Solution

Use the JavaScript indexOf( ) string method on the longer string section, passing the shorter string as an argument. If the shorter string is inside the larger string, the method returns a zero-based index integer of the start position of the smaller string within the larger string. If the shorter string is not in the larger string, the method returns -1.

For logic that needs to branch if the smaller string is not contained by the larger string, use the following construction:

if (largeString.indexOf(shortString) =  = -1) {
    // process due to missing shortString
}

PREVIEW

                                                                          

Not a subscriber?

Start A Free Trial


  
  • Creative Edge
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint