这并不完美,但可以,这是一个演示:
(这个Demo只是找常用词)
- 它使用正则表达式分割文本
- 然后数单词
- 然后返回最常用的词
var data = document.getElementById("data").value;
var allWords = data.split(/\b/);
var wordCountList = {};
allWords.forEach(function(word){
if(word !== " "){
if(!wordCountList.hasOwnProperty(word)){
wordCountList[word] = {word: word, count:0};
}
wordCountList[word].count++;
}
})
var maxCountWord = {count:0};
for(var propName in wordCountList){
var currentWord = wordCountList[propName];
if(maxCountWord.count<currentWord.count){
maxCountWord = currentWord;
}
}
console.info(maxCountWord);
textarea{
width:100%;
height:100px;
}
<textarea id="data" >
<!-- start slipsum code -->
The path of the righteous man is beset on all sides by the iniquities of the selfish and the tyranny of evil men. Blessed is he who, in the name of charity and good will, shepherds the weak through the valley of darkness, for he is truly his brother's keeper and the finder of lost children. And I will strike down upon thee with great vengeance and furious anger those who would attempt to poison and destroy My brothers. And you will know My name is the Lord when I lay My vengeance upon thee.
<!-- end slipsum code -->
</textarea>
<div id="result"></div>
替换这个词你也可以用正则表达式:
(这个Demo只是替换了一个常用词)
function freewordchoice (free, word, choice){
var data = document.getElementById("data").innerHTML;
var replaceExpression = new RegExp("\\b"+word+"\\b","gi");
console.info(replaceExpression);
data =data.replace(replaceExpression, free + word + choice);
document.getElementById("result").innerHTML = data;
}
freewordchoice("<b>", "the", "</b>");
<b>Before:</b>
<div id="data" >
<!-- start slipsum code -->
The path of the righteous man is beset on all sides by the iniquities of the selfish and the tyranny of evil men. Blessed is he who, in the name of charity and good will, shepherds the weak through the valley of darkness, for he is truly his brother's keeper and the finder of lost children. And I will strike down upon thee with great vengeance and furious anger those who would attempt to poison and destroy My brothers. And you will know My name is the Lord when I lay My vengeance upon thee.
<!-- end slipsum code -->
</div>
<br/><br/>
<b>After:</b>
<div id="result" >
</div>
更新:
问题出在这一行
common = 'the,a,do,in,with,this,so,that,of,and,not,did,when,what,were,went,was,as,
if,who,had,at,can,you,which,while,will,to,till,then,them,their,she,
he,once,out,no,must,many,me,is,it,his,him,her,about,have,i,has,your,
would,where,whom,s,on,from,for,by,but,all,said,my,';
问题出在字符串末尾,said,my,'; 删除最后一个逗号,它应该可以工作,如下所示:
common = 'the,a,do,in,with,this,so,that,of,and,not,did,when,what,were,went,was,as,
if,who,had,at,can,you,which,while,will,to,till,then,them,their,she,
he,once,out,no,must,many,me,is,it,his,him,her,about,have,i,has,your,
would,where,whom,s,on,from,for,by,but,all,said,my';
由于通过最后一个逗号,最后一个单词是一个空字符串。