PDA

View Full Version : Find specific text within a string?



jlizarraga
07-31-2008, 08:33 AM
Suppose I wanted to know if the string "43fdsfhipposa97sad" contained the smaller string "hippo". How would I go about determining that?

Thanks!

jscheuer1
07-31-2008, 08:38 AM
if (/hippo/.test("43fdsfhipposa97sad"))
alert("It's in there!");

Or, more useful in a way:



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

rangana
07-31-2008, 09:24 AM
Another way to go is to use:

indexOf() (http://www.w3schools.com/jsref/jsref_indexOf.asp):


var str='43fdsfhipposa97sad';
if (str.indexOf('hippo')>1)
alert("It's in there!");

match() (http://www.w3schools.com/jsref/jsref_match.asp):


var str='43fdsfhipposa97sad';
if (str.match('hippo'))
alert("It's in there!");

jscheuer1
07-31-2008, 11:36 AM
Another way to go is to use:

indexOf() (http://www.w3schools.com/jsref/jsref_indexOf.asp):


var str='43fdsfhipposa97sad';
if (str.indexOf('hippo')>1)
alert("It's in there!");

match() (http://www.w3schools.com/jsref/jsref_match.asp):


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.

jlizarraga
08-01-2008, 06:06 AM
Thanks guys!