1

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?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Sarahpre
  • 35
  • 3
  • 3
    Compare the return value of indexOf to zero: http://stackoverflow.com/questions/1767246/javascript-check-if-string-begins-with-something – Vikdor Sep 18 '12 at 17:37
  • Vikdor, that doesn't work because indexOf matches anywhere in the string, which I don't want. I don't wnat anywhere in the string only from the start. – Sarahpre Sep 18 '12 at 17:38
  • 2
    @Sarahpre Vikdor's point is that if it does match at the _start of the string_ the result will be zero – Alnitak Sep 18 '12 at 17:40

3 Answers3

4

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 ) {}
Musa
  • 96,336
  • 17
  • 118
  • 137
1
<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.

Micah
  • 313
  • 1
  • 4
0

What you describe means you want compare with zero:

if ( "upload a file".indexOf(user_input.toLowerCase()) == 0) { }
Michal Klouda
  • 14,263
  • 7
  • 53
  • 77