gpt4 book ai didi

javascript - 字数计数器可以工作,但逗号和句号有问题

转载 作者:行者123 更新时间:2023-11-28 16:58:11 24 4
gpt4 key购买 nike

我有一个小程序来显示一个单词在段落中重复的次数,但由于某种原因我无法拆分逗号和句点。因此,脚本将 'Cola''Cola,''Cola.' 视为不同的单词。

如何忽略标点符号?

<script>
function count() {
var inputVal = document.getElementById("textInput").value; //get text to count
var storyWords = inputVal.split(' '); // split words

var filterWords = storyWords.map(function(x) {
return x.toLowerCase()
});
filterWords.sort();

var current = null;
var cnt = 0;

for (var i = 0; i < filterWords.length; i++) {
if (filterWords[i] != current) {
if (cnt > 1) {
// var h = document.getElementById('fillIn');
var table = document.getElementById('myTable');
var row = table.insertRow(1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = current;
cell2.innerHTML = cnt;

var h = document.createElement("LI");
var t = document.createTextNode(current + ' // --> ' + cnt + ' times');
h.appendChild(t);
document.body.appendChild(h);

}
current = filterWords[i];
cnt = 1;
} else {
cnt++;
}
}

if (cnt > 1) {

var h = document.createElement("LI");
//var h = document.getElementById('fillIn');
var t = document.createTextNode(current + ' // --> ' + cnt + ' times');
h.appendChild(t);
document.body.appendChild(h);
}

document.getElementById("clickMe").disabled = true;
}

// On button click, execute the function
document.getElementById("clickMe").onclick = function() {
count();
}
</script>

enter image description here

最佳答案

替换

var storyWords = inputVal.split(' '); // split words

var storyWords = inputVal.split(/[ ,.]/);

关于javascript - 字数计数器可以工作,但逗号和句号有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58480382/

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