Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript indexOf not working

Tags:

javascript

The following code looks for the name of a person in a message that they have entered using the indexOf method.

However it is returning the not present result even when the name is present. If I only Darren as the cardMessage it works.

Can anyone point out what is wrong.

<%
firstName = "Darren"
cardMessage = "Is Darren in the message?"
cardMessage = CleanX(cardMessage)
firstName = UCase(firstName)
cardMessage = UCase(cardMessage)

Function CleanX(strString)
Set regEx = New RegExp
regEx.Pattern = "[^a-z0-9 ]+"
regEx.IgnoreCase = True
regEx.Global = True
CleanX = regEx.Replace(strString, "")
End Function
%>
<p><%=cardMessage%></p>
<p><%=firstName%></p>
<a href="javascript:check_message()">Click Here</a>
<script type="text/javascript">

s1 = new String("<%=firstName%>")
s2 = new String("<%=cardMessage%>")

function check_message()
{
var purchaser=s1;
var purchaser_ok=purchaser.indexOf(s2);
if (purchaser_ok==-1)
{ 
confirm('Name is NOT in message');
}
else
alert('Name is in message');
}
</script>
like image 267
Darren Cook Avatar asked Jun 28 '11 12:06

Darren Cook


2 Answers

You're doing it backwards. It should be

var purchaser_ok = s2.indexOf(purchaser);

The ".indexOf()" function checks to see whether the argument you pass into it is in the string that's used as the receiver (the context object; that is, the string before the "." when you call it).

like image 136
Pointy Avatar answered Oct 23 '22 23:10

Pointy


You have it backwards.

s2.indexOf(purchaser)

like image 1
James Montagne Avatar answered Oct 23 '22 23:10

James Montagne