Link to home
Start Free TrialLog in
Avatar of willa666
willa666Flag for United States of America

asked on

like operator?

Is their such a thing as a like in javascript? I have a string and i need to find out if it is like another string.
Avatar of hongjun
hongjun
Flag of Singapore image

Try this

<script>
var str1, str2, str3;

str1 = "Hello World";
str2 = "Hello";
str3 = "Not in";

alert(str1.indexOf(str2));
alert(str1.indexOf(str3));
</script>
indexOf will give you -1 like in the situation above where str3 is not in str1
indexOf will give you >= 0 (position start from 0) where str2 is first found in str1.
Avatar of willa666

ASKER

coolio!

thats works a treat! what if i want the end to match?
Don't understand
well instead of it getting the indexof a string it looks for the end of the string to match.

u c
indexOf will find it anywhere.

Looking for hello in all of these:

<script>
var str1, str2, str3;

str1 = "Hello";
str2 = "Hello World";
str3 = "Not in here, it isn't";
str4 = "Well, you didn't even say Hello when I saw you yesterday";

alert(str2.indexOf(str1));
alert(str3.indexOf(str1));
alert(str4.indexOf(str1));
</script>

These will return 0, -1, 26 .  Any value>=0 indicates a match.

You should probably turn all strings to lowercase before comparing, because you wouldn't find a match for "Hello" in "You say goodbye and I say hello." because of the difference in capitalization.

Peace and joy to you.
mvan
ASKER CERTIFIED SOLUTION
Avatar of mvan01
mvan01
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial