繁体   English   中英

将全部或部分字符串与javascript匹配

[英]match full or part of string with javascript

我想将用户输入与给定的字符串进行比较,例如“ hello”,比较的“ hello”应返回true,表示该部分很容易,但我也希望“ h”,“ he”,“ hel”等返回true,但不返回“ lo”

您将如何使用javascript处理此问题?

快速简单的方法:

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
}

您需要使用indexOf()函数。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM