gpt4 book ai didi

javascript - 单词计数器应用程序中的错误

转载 作者:行者123 更新时间:2023-11-30 12:31:52 26 4
gpt4 key购买 nike

我创建了 this application .该程序计算文本中的单词数。

但是当我打印第一个字符(任何字符)作为一个单词时我有错误,我不明白为什么。

这里是 jQuery:

counter = function () {
var value = $('#text').val();

if (value.length == 0) {
$('#wordCount').html(0);
$('#totalChars').html(0);
$('#charCount').html(0);
$('#charCountNoSpace').html(0);
return;
}
//var regex1 = /[^A-Za-z_]/gim;
var regex1 = /[^a-z_]/gim;
var regex2 = /\s+/gi;
var textTrimmed = value.replace(regex1, '');
var wordCount = textTrimmed.trim().replace(regex2, ' ').split(' ').length;

var totalChars = value.length;
var charCount = value.trim().length;
var charCountNoSpace = value.replace(regex1, '').length;

$('#textFiltered').html(textTrimmed.trim().replace(regex2, ' '));
$('#textTrimmed').html(textTrimmed);
$('#wordCount').html(wordCount);
$('#totalChars').html(totalChars);
$('#charCount').html(charCount);
$('#charCountNoSpace').html(charCountNoSpace);
};

$(document).ready(function () {
$('#count').click(counter);
$('#text').change(counter);
$('#text').keydown(counter);
$('#text').keypress(counter);
$('#text').keyup(counter);
$('#text').blur(counter);
$('#text').focus(counter);
});

HTML代码:

<!DOCTYPE html>
<html>
<head>
<title>Copy &amp; Paste, Word &amp; Character counter</title>
</head>
<body>
<div id="border">
<textarea id='text'></textarea>
</div>
<button id="count">Count</button>
<div id="result">

Words: <span id="wordCount">0</span><br/>
Total Characters(including trails): <span id="totalChars">0</span><br/>
Characters (excluding trails): <span id="charCount">0</span><br/>
Characters (excluding all spaces): <span id="charCountNoSpace">0</span>
</div>
</body>
</html>

我该如何修复该错误?

最佳答案

你的问题不是很清楚,但据我了解,我认为问题出在下面这行

var wordCount = textTrimmed.trim().replace(regex2, ' ').split(' ').length;

改成这样

var wordCount = value.trim().split(' ').length;

JSFIDDLE

关于javascript - 单词计数器应用程序中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27473231/

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