[英]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' 我想将用户输入与给定的字符串进行比较,例如“ hello”,比较的“ hello”应返回true,表示该部分很容易,但我也希望“ h”,“ he”,“ hel”等返回true,但不返回“ lo”
How would you approach this with javascript? 您将如何使用javascript处理此问题?
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
}
you need to use indexOf() function. 您需要使用indexOf()函数。
var hello = "hello";
if(hello.indexOf("he")===0){
//its in.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.