gpt4 book ai didi

javascript - 如何计算字符串javascript函数中的特殊字符,该函数只接受@#

转载 作者:行者123 更新时间:2023-12-02 14:03:51 25 4
gpt4 key购买 nike

在我的项目中,我的任务是对用户输入的字符进行计数并显示计数,它工作正常,但我想添加仅允许特殊字符的正则表达式

<!DOCTYPE html>
<script type="text/javascript">
function countChars(countfrom,displayto)
{
var len = document.getElementById(countfrom).value.length;
document.getElementById(displayto).innerHTML = len;
}
</script>


<label>Enter Character</label><br>
<textarea id="data" cols="40" rows="5"
onkeyup="countChars('data','charcount');" onkeydown="countChars('data','charcount');"
onmouseout="countChars('data','charcount');">
</textarea><br>
<span id="charcount">0</span>
</html>

最佳答案

一个工作示例:

<label>Enter Character</label><br>
<textarea id="data" cols="40" rows="5"
onkeyup="countChar(this, '@', 'charcount');" onkeydown="countChar(this, '@', 'charcount');"
onmouseout="countChar(this, '@', 'charcount');">
</textarea><br>
<span id="charcount">0</span>


<script>
function countChar(container, char, targetId) {
target = document.getElementById(targetId);
var regEx = new RegExp(char, 'g');
var matches = container.value.match(regEx);

if(matches) {
target.innerHTML = matches.length;
}
}
</script>

关于javascript - 如何计算字符串javascript函数中的特殊字符,该函数只接受@#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40212979/

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