【问题标题】:Only allow whitespace after comma and restrict special characters in text field using regex仅允许逗号后的空格并使用正则表达式限制文本字段中的特殊字符
【发布时间】: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


【解决方案1】:

在您的代码 .replace(/[^0-9,]/g, "") 中,您将删除除数字和逗号之外的所有字符,不再允许使用字符 a-z。

您可以先删除除[^a-zA-Z0-9, ]+ 之外的所有字符,然后在support a lookbehind 的浏览器中,您可以允许前面不直接有逗号的空格。

function checkKey() {
  const clean = this.value
    .replace(/[^a-zA-Z0-9, ]+/g, "")
    .replace(/(?<!,) /g, "");
  if (clean !== this.value) this.value = clean;
}

document.querySelector('input').oninput = checkKey;
<form>
  <input type="text">
</form>

【讨论】:

    【解决方案2】:

    要删除非逗号字符后的所有空格,您可以使用此解决方案而无需后视:

    .replace(/(^|[^,])\s+/g, "$1")
    

    this regex demo详情

    • (^|[^,]) - 捕获组 1($1 指此组值):字符串开头 (^) 或 (|) 任何非逗号字符 ([^,])
    • \s+ - 一个或多个空格。

    在您的代码中:

    function checkKey() {
        var clean = this.value.replace(/[^\d,]/g, "").replace(/(^|[^,])\s+/g, "$1");
        if (clean !== this.value) {
            this.value = clean;
        }
    }
    

    【讨论】:

    • @user992731 当您需要支持任何 JS 环境时,应该首选此解决方案,因为其中一些环境,如撰写本文时的 Safari,不支持lookbehinds。
    猜你喜欢
    • 1970-01-01
    • 2019-03-06
    • 1970-01-01
    • 1970-01-01
    • 2015-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多