[英]javascript find character in string from reverse
我想在我的网站上使用特定的搜索功能。
即:在搜索文本框用户类型
姓名:管理员,年龄:30
所以当用户键入uname并按回车键然后“:”自动添加并键入值“admin”然后再次按回车键“,”自动添加时,我需要那种类型的javascript代码。 等等...
请给我做这件事的任何提示
当我添加“:”或“,”时,我很困惑
先感谢您。
如果我正确理解您的问题,这应该有效:
const input = document.getElementById('search') input.addEventListener('keypress', e => { if (e.keyCode === 13) { e.preventDefault() const value = e.target.value if (!value) return if (value.match(/^(\\w+:\\w+,)*\\w+$/)) { e.target.value = value + ':' } else if (value.match(/^(\\w+:\\w+,)*\\w+:\\w+$/)) { e.target.value = value + ',' } } })
<input type="text" id="search">
或者,如果您想清理输入和存储数据:
const input = document.getElementById('search') let data = '' input.addEventListener('keypress', e => { if (e.keyCode === 13) { e.preventDefault() const value = e.target.value if (!value) return if (!data || data.match(/^(\\w+:\\w+,)*$/)) { data += value + ':' e.target.value = '' console.log(data) } else if (data.match(/^(\\w+:\\w+,)*\\w+:$/)) { data += value + ',' e.target.value = '' console.log(data) } } })
<input type="text" id="search">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.