Mark
Mark

Reputation: 3197

match full or part of string with javascript

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?

Upvotes: 0

Views: 39

Answers (2)

Idan Magled
Idan Magled

Reputation: 2216

you need to use indexOf() function.

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

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

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
}

Upvotes: 3

Related Questions