【发布时间】:2021-05-19 06:04:00
【问题描述】:
我试图限制用户在字符后输入空格或按空格键(除非他们输入逗号)以及限制除数字和字母之外的所有特殊字符。
所需的输出类似于:“ab, c”或“abc, def, g, h...” 用户只能在逗号后使用空格或按空格键。逗号是唯一允许的特殊字符。
到目前为止我所拥有的,但它只允许使用 1 个逗号:
function checkKey() {
var clean = this.value.replace(/[^0-9,]/g, "")
.replace(/(,.*?),(.*,)?/, "$1");
// don't move cursor to end if no change
if (clean !== this.value) this.value = clean;
}
// demo
document.querySelector('input').oninput = checkKey;
【问题讨论】:
-
可能在非逗号或字符串开头后删除空格?
.replace(/(^|[^,])\s/, "$1");? -
忘了
g,你需要.replace(/(^|[^,])\s+/g, "$1");
标签: javascript regex