Javascript indexOf 不工作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6506800/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript indexOf not working
提问by Darren Cook
The following code looks for the name of a person in a message that they have entered using the indexOf method.
以下代码在他们使用 indexOf 方法输入的消息中查找人员的姓名。
However it is returning the not present result even when the name is present. If I only Darren as the cardMessage it works.
但是,即使名称存在,它也会返回不存在的结果。如果我只将 Darren 作为 cardMessage,它就可以工作。
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>
采纳答案by Pointy
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).
".indexOf()" 函数检查您传递给它的参数是否在用作接收器的字符串中(上下文对象;即,当您调用它时,"." 之前的字符串)。
回答by James Montagne
You have it backwards.
你把它倒过来了。
s2.indexOf(purchaser)
s2.indexOf(purchaser)