JavaScript string matching only at the start versus using indexOf?

耗尽温柔 提交于 2019-12-25 18:27:03

问题


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.

This should match:

"upload"
"u"
"upload a"

This should not match, because the string does not match from the start:

"a"
"file"

Are there any suggestions on how to make this happen with indexOf?


回答1:


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 ) {}



回答2:


What you describe means you want compare with zero:

if ( "upload a file".indexOf(user_input.toLowerCase()) == 0) { }



回答3:


<script>
user_input = "upload a file"
if ( "upload a file".**substr**(0, user_input.length) == user_input.toLowerCase()) {}
</script>

Use the inputs to your advantage...

http://www.w3schools.com/jsref/jsref_substr.asp

Grab first X characters of the string, and make sure the whole string matches or any number of the characters you would like.



来源:https://stackoverflow.com/questions/12482136/javascript-string-matching-only-at-the-start-versus-using-indexof

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!