gpt4 book ai didi

javascript - Js,如何忽略文本框中贡献文本长度的符号?

转载 作者:行者123 更新时间:2023-11-28 12:15:23 25 4
gpt4 key购买 nike

我的目标是计算文本框中非符号的文本。例如,如果用户输入 email_ex_3/2@mail.com,文本的原始长度为 21,但我的目标是忽略这些符号,使长度变为 16。

我所能想到的就是使用for循环来检查这些符号,但我认为这是非常丑陋的。

JS

function test() {
alert(document.getElementById("firstText").value.length);
}

HTML

<input type="text" id="firstText" />
<button onclick="test()">Submit</button>

最佳答案

您可以使用正则表达式将所有非单词字符替换为空字符串,并检查结果的长度:

const getLen = str => str.replace(/[^A-Za-z0-9]/g, '').length;
console.log(getLen('email_ex_3/2@mail.com'));

关于javascript - Js,如何忽略文本框中贡献文本长度的符号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50811765/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com