0

I want to compare user input to a given string eg 'hello' compared 'hello' should return true that part is easy but I also want 'h', 'he', 'hel' etc to return true but not 'lo'

How would you approach this with javascript?

2 Answers 2

3

A quick and simple way:

var match = "hello"; var test = "hel"; if( match.substr(0,test.length) == test) { // looking good! // optionally, add this to the condition: && test.length > 0 // otherwise an empty test string would match } 
Sign up to request clarification or add additional context in comments.

4 Comments

That should be match.substring(0, test.length) === test.
@SpiderPig It should indeed. 's'what I get for writing PHP for several hours straight XD
any advantages / disadvantages between this solution and idans?
@Ir1sh Idan's solution it much less efficient when the string doesn't match (it will try to match at every position, even though you're only interested in the start). This one is more efficient because it fails immediately.
1

you need to use indexOf() function.

var hello = "hello"; if(hello.indexOf("he")===0){ //its in. } 

3 Comments

That should be === 0, not > 0.
no, the string can be on the first position in the search string and its return 0.
@IdanMagled That's what OP is asking for - a match from the start.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.