JavaScript字符串仅在开始时与使用indexOf匹配? [英] JavaScript string matching only at the start versus using indexOf?
本文介绍了JavaScript字符串仅在开始时与使用indexOf匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我当前正在匹配用户输入,如下所示:
I currently am matching user input as follows:
user_input = "upload a file"
if ( "upload a file".indexOf(user_input.toLowerCase()) > -1 ) {}
这工作正常,但问题是,它与我不想要的文件"匹配.我希望只有在开头正确的情况下才能匹配.
This work fine but the problem is, it matches "a file" which I don't want. I want it to only match if the beginning is correct.
这应该匹配:
"upload"
"u"
"upload a"
这不应该匹配,因为字符串从一开始就不匹配:
This should not match, because the string does not match from the start:
"a"
"file"
关于如何使用indexOf
实现这一目标,是否有任何建议?
Are there any suggestions on how to make this happen with indexOf
?
推荐答案
indexOf
返回匹配的索引,因此,如果要在开始时测试它是否匹配,只需检查它是否返回0
indexOf
return the index of the match, so if you want to test if it match at the beginning just check if it returns 0
user_input = "upload a file"
if ( "upload a file".indexOf(user_input.toLowerCase()) == 0 ) {}
这篇关于JavaScript字符串仅在开始时与使用indexOf匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文