gpt4 book ai didi

javascript - 当我在 <textarea> 上按 Enter 时,单词计数器不显示该单词

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

Codepen project link

我如何更改正则表达式来计算任何人输入的单词并在其上写入内容

(countWords=()=>{
s = document.getElementById("inputString").value;
s = s.replace(/(^\s*)|(\s*$)/gi,"");
s = s.replace(/[ ]{2,4}/gi," ");
s = s.replace(/\n /,"\n");
document.getElementById("wordcount").value = s.split(' ').length;

})()
<textarea name="inputString" id="inputString" cols="50" rows="4">Text to count</textarea>
<br>
<input type="button" name="Convert" value="Count Words" onClick="countWords();">
<input name="wordcount" id="wordcount" type="text" value="" size="6">

最佳答案

您可以使用 trim() 从开头/结尾去除空格,然后用 1 个以上空格字符分割:

s.trim().split(/\s+/).length

或者,您可以使用匹配方法来计算所有非空白字符 block :

document.getElementById("wordcount").value = s.match(/\S+/g)?.length || 0;

JS 演示(带有可选链接):

(countWords=()=>{
s = document.getElementById("inputString").value;
document.getElementById("wordcount").value = s.match(/\S+/g)?.length || 0;
})()
<textarea name="inputString" id="inputString" cols="50" rows="4">Text to count</textarea>
<br>
<input type="button" name="Convert" value="Count Words" onClick="countWords();">
<input name="wordcount" id="wordcount" type="text" value="" size="6">

JS 演示(无可选链接):

(countWords=()=>{
s = document.getElementById("inputString").value;
var m = s.match(/\S+/g);
document.getElementById("wordcount").value = (m ? m.length : 0);
})()
<textarea name="inputString" id="inputString" cols="50" rows="4">Text to count</textarea>
<br>
<input type="button" name="Convert" value="Count Words" onClick="countWords();">
<input name="wordcount" id="wordcount" type="text" value="" size="6">

关于javascript - 当我在 &lt;textarea&gt; 上按 Enter 时,单词计数器不显示该单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61061590/

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