Results 1 to 5 of 5

Thread: Find specific text within a string?

  1. #1
    Join Date
    Apr 2008
    Location
    San Diego, CA
    Posts
    352
    Thanks
    57
    Thanked 6 Times in 6 Posts

    Default Find specific text within a string?

    Suppose I wanted to know if the string "43fdsfhipposa97sad" contained the smaller string "hippo". How would I go about determining that?

    Thanks!

  2. #2
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    Code:
    if (/hippo/.test("43fdsfhipposa97sad"))
    alert("It's in there!");
    Or, more useful in a way:

    Code:
    var teststring = "43fdsfhipposa97sad";
    if (/hippo/.test(teststring))
    alert("It's in there!");
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  3. The Following User Says Thank You to jscheuer1 For This Useful Post:

    jlizarraga (08-01-2008)

  4. #3
    Join Date
    Feb 2008
    Location
    Cebu City Philippines
    Posts
    1,160
    Thanks
    17
    Thanked 277 Times in 275 Posts

    Default

    Another way to go is to use:
    • indexOf():
      Code:
      var str='43fdsfhipposa97sad';
      if (str.indexOf('hippo')>1)
      alert("It's in there!");
    • match():
      Code:
      var str='43fdsfhipposa97sad';
      if (str.match('hippo'))
      alert("It's in there!");
    Learn how to code at 02geek

    The more you learn, the more you'll realize there's much more to learn
    Ray.ph!

  5. #4
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    Quote Originally Posted by rangana View Post
    Another way to go is to use:
    • indexOf():
      Code:
      var str='43fdsfhipposa97sad';
      if (str.indexOf('hippo')>1)
      alert("It's in there!");
    • match():
      Code:
      var str='43fdsfhipposa97sad';
      if (str.match('hippo'))
      alert("It's in there!");
    Both of these are less efficient than test(). However, depending upon what other information (if any) you may want to get out of the string (str in your examples), those other methods can prove useful.
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  6. #5
    Join Date
    Apr 2008
    Location
    San Diego, CA
    Posts
    352
    Thanks
    57
    Thanked 6 Times in 6 Posts

    Default

    Thanks guys!

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •