问题描述
我实际上正在使用一个系统,该系统会在用户填写表单输入时向用户提出建议,这是他在上次访问网站时在此表单字段中键入的单词(实际上是Google样的自动完成表单) 。
我的表单很基本:名字的输入和姓的输入。
由于正则表达式,我想知道是否有一种方法可以检查键入的单词是否与我之前存储在LocalStorage中的单词匹配。
范例 :
我存储在localStorage中的单词是“ Matthew”。
将匹配的键入单词是:“ M”,“ Ma”,“ Mat”,“ Matt”,“ Matth”,“ Matthe”和“ Matthew”。
预先感谢您的帮助 :)
1楼
当我需要检查正则表达式时,可以使用以下服务: : 。
但是对于您的任务,我认为您只需要一个indexOf()函数:
var userName = 'Matthew'; var searchTerm = 'Ma'; var indexOfFirst = userName.indexOf(searchTerm); console.log('The index of the first "' + searchTerm + '" from the beginning is ' + indexOfFirst);
更多信息: :
2楼
在较新的浏览器中,有一个string.startsWith(...)
函数,它将告诉您字符串是否以输入开头
参考: :
如果您需要旧版浏览器的支持,则可以使用上一页中的pollyfill:
if (!String.prototype.startsWith) {
Object.defineProperty(String.prototype, 'startsWith', {
value: function(search, pos) {
pos = !pos || pos < 0 ? 0 : +pos;
return this.substring(pos, pos + search.length) === search;
}
});
}