【发布时间】:2020-07-19 05:39:01
【问题描述】:
我正在尝试删除特殊字符,如 @、# 等,除了带有空字符串的空格
<input type='text' onkeyup="this.value.replace('/[^a-zA-Z0-9]/g', '')">
但它不起作用
【问题讨论】:
标签: javascript regex
我正在尝试删除特殊字符,如 @、# 等,除了带有空字符串的空格
<input type='text' onkeyup="this.value.replace('/[^a-zA-Z0-9]/g', '')">
但它不起作用
【问题讨论】:
标签: javascript regex
您需要删除正则表达式模式周围的quotes,并将替换值分配给this.value,因为replace 方法会创建一个新字符串,它不会修改您正在操作的字符串
<input type='text' onkeyup="this.value = this.value.replace(/[^a-zA-Z0-9]/g, '')">
【讨论】:
以这种方式更改值不会替换原始值。它给你一个新的字符串。完成替换后,您必须将其分配回this.value,这样就可以了。
此外,正则表达式模式不需要用引号引起来。它以“/”开头和结尾。所以你必须删除它。
更多阅读 - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
<input type='text' onkeyup="this.value = this.value.replace(/[^a-zA-Z0-9]/g,'')">
内联事件侦听器被认为是不好的做法,您可能应该在 JS 领域使用 addEventListener 这样做。
【讨论】:
使用内联事件处理程序通常是not a good idea。替代方案:使用 input 事件和委托处理程序:
{
document.addEventListener("input", textOnly, true);
function textOnly(evt) {
const origin = evt.target;
if (origin.id === "textOnly") {
origin.value = origin.value
.replace(/[^a-z0-9]$/i, "");
// ^ only the last inputted character
}
}
}
<input type="text" id="textOnly">
【讨论】: