Javascript 计算字符串中的单词
我试图用这种方式计算文本中的字数:Javascript 计算字符串中的单词,javascript,Javascript,我试图用这种方式计算文本中的字数: function WordCount(str) { var totalSoFar = 0; for (var i = 0; i < WordCount.length; i++) if (str(i) === " ") { // if a space is found in str totalSoFar = +1; // add 1 to total so far } totalsoFar += 1;
function WordCount(str) {
var totalSoFar = 0;
for (var i = 0; i < WordCount.length; i++)
if (str(i) === " ") { // if a space is found in str
totalSoFar = +1; // add 1 to total so far
}
totalsoFar += 1; // add 1 to totalsoFar to account for extra space since 1 space = 2 words
}
console.log(WordCount("Random String"));
使用方括号,而不是圆括号:
str[i] === " "
或charAt
:
str.charAt(i) === " "
您也可以使用.split()
:
我认为这个方法比你想要的要多
var getWordCount = function(v){
var matches = v.match(/\S+/g) ;
return matches?matches.length:0;
}
在改造车轮之前,请尝试这些方法 从 从 从-这将是最好的方法
function WordCount(str) {
return str.split(' ')
.filter(function(n) { return n != '' })
.length;
}
作者注释:
您可以调整此脚本以任意方式计算字数。
重要的部分是s.split('').length
-这计算
空间。
脚本尝试在计数之前删除所有多余的空格(双空格等)。
如果文本中包含两个单词,且两个单词之间没有空格,则将它们计为一个单词,例如“第一句话”
.下一句的开头”
var-cnt;
函数wordcount(count){
var words=count.split(/\s/);
cnt=单词长度;
var ele=document.getElementById('w_count');
元素值=碳纳米管;
}
文件。填写(“”);
计算字符串中单词的另一种方法。此代码统计仅包含字母数字字符和“”、“'”、“-”、“'”字符的单词
清理字符串后,可以匹配非空白字符或单词边界 下面是两个简单的正则表达式,用于捕获字符串中的单词:
- 非空白字符序列:
/\S+/g
- 单词边界之间的有效字符:
/\b[a-z\d]+\b/g
/*将控制台输出重定向到HTML.*/document.body.innerHTML='';console.log=函数{document.body.innerHTML+=s+'\n';};
/*字符串格式.*/String.format | |(String.format=function(f){return function(a){return f.replace(/{(\d+)}/g,function(m,n){return“undefined”!=typeof a[n]?a[n]:m}([].slice.call(arguments,1));
//^忽略上面的代码^
// =================
//清理并匹配字符串中的子字符串。
函数extractSubstr(str,regexp){
返回str.replace(/[^\w\s]|(/ug'))
.替换(/\s+/g')
.toLowerCase().match(regexp)| |[];
}
//通过搜索非空白字符序列查找单词。
函数getWordsByNonWhiteSpace(str){
返回extractSubstr(str,/\S+/g);
}
//通过在单词边界之间搜索有效字符来查找单词。
函数GetWordsByWordBounders(str){
返回extractSubstr(str,/\b[a-z\d]+\b/g);
}
//用法示例。
var edisonQuote=“我没有失败。我刚刚找到了10000种行不通的方法。”;
var words1=getWordsByNonWhiteSpace(edisonQuote);
var words2=getwordsbywordbounders(edisonQuote);
console.log(String.format(“{0}”-Thomas Edison\n\n通过:\n',edisonQuote进行单词计数);
log(String.format('-非空白:({0})[{1}]',words1.length,words1.join(','));
log(String.format('-单词边界:({0})[{1}]',words2.length,words2.join(','))代码>
body{font-family:monospace;white-space:pre;font-size:11px;}
您的代码中有一些错误
function WordCount(str) {
var totalSoFar = 0;
for (var i = 0; i < str.length; i++) {
if (str[i] === " ") {
totalSoFar += 1;
}
}
return totalSoFar + 1; // you need to return something.
}
console.log(WordCount("Random String"));
精确值可以相差约1个单词,但也可以计算没有空格的单词边框,例如“word.word”。它不计算不包含字母或数字的单词。我知道已经很晚了,但是这个正则表达式应该可以解决您的问题。这将匹配并返回字符串中的字数。而不是您标记为解决方案的那个,它将空格单词计算为2个单词,尽管实际上只有1个单词
function countWords(str) {
var matches = str.match(/\S+/g);
return matches ? matches.length : 0;
}
到目前为止,我找到的最简单的方法是使用带有split的正则表达式
var calculate=function(){
var string=document.getElementById('input')。值;
var length=string.split(/[^\s]+/).length-1;
document.getElementById('count')。innerHTML=长度;
};代码>
我的超级文本,包含7个单词。
算计
7个单词
String.prototype.match
返回一个数组,然后我们可以检查长度
我发现这种方法最具描述性
var str = 'one two three four five';
str.match(/\w+/g).length;
@7-isnotbad给出的答案非常接近,但不包括单字行。这是一个解决方案,它似乎解释了单词、空格和换行符的所有可能组合
function countWords(s){
s = s.replace(/\n/g,' '); // newlines to space
s = s.replace(/(^\s*)|(\s*$)/gi,''); // remove spaces from start + end
s = s.replace(/[ ]{2,}/gi,' '); // 2 or more spaces to 1
return s.split(' ').length;
}
也许有一种更有效的方法可以做到这一点,但这对我来说是有效的
function countWords(passedString){
passedString = passedString.replace(/(^\s*)|(\s*$)/gi, '');
passedString = passedString.replace(/\s\s+/g, ' ');
passedString = passedString.replace(/,/g, ' ');
passedString = passedString.replace(/;/g, ' ');
passedString = passedString.replace(/\//g, ' ');
passedString = passedString.replace(/\\/g, ' ');
passedString = passedString.replace(/{/g, ' ');
passedString = passedString.replace(/}/g, ' ');
passedString = passedString.replace(/\n/g, ' ');
passedString = passedString.replace(/\./g, ' ');
passedString = passedString.replace(/[\{\}]/g, ' ');
passedString = passedString.replace(/[\(\)]/g, ' ');
passedString = passedString.replace(/[[\]]/g, ' ');
passedString = passedString.replace(/[ ]{2,}/gi, ' ');
var countWordsBySpaces = passedString.split(' ').length;
return countWordsBySpaces;
}
它能够将以下所有内容识别为单独的单词:
abc,abc
=2个字,
abc/abc/abc
=3个字(可用于向前和向后斜杠),
abc.abc
=2个字,
abc[abc]abc
=3个字,
abc;abc
=2个字,
(我尝试过的其他一些建议将上面的每个示例计算为1 x单词)
它还:
- 忽略所有前导空格和尾随空格
- 将一个字母后跟一个新行计算为一个单词-我发现本页给出的一些建议不算数,例如:
a
a
a
a
a
有时计算为0 x单词,而其他函数仅计算为1 x单词,而不是5 x单词)
如果有人对如何改进它或更清洁/更高效有任何想法,请加上2美分!
希望这能帮助别人 下面是一个计算HTML代码中字数的函数:
$(this).val()
.replace(/(( )|(<[^>]*>))+/g, '') // remove html spaces and tags
.replace(/\s+/g, ' ') // merge multiple spaces into one
.trim() // trim ending and beginning spaces (yes, this is needed)
.match(/\s/g) // find all spaces by regex
.length // get amount of matches
$(this.val()
.replace(/(()|(]*>)+/g',)//删除html空格和标记
.replace(//\s+/g',)//将多个空格合并为一个空格
.trim()//修剪结束和开始空格(是,这是必需的)
.match(//\s/g)//按正则表达式查找所有空格
.length//获取匹配的数量
说明:
/([^\u0000-\u007F]|\w)
匹配单词字符-这很好->正则表达式为我们做了大量工作。(此模式基于以下SO答案:@Landeeyo)
+
匹配前面指定的单词字符的整个字符串-因此我们基本上对单词字符进行分组
function WordCount(str) {
var totalSoFar = 0;
for (var i = 0; i < str.length; i++) {
if (str[i] === " ") {
totalSoFar += 1;
}
}
return totalSoFar + 1; // you need to return something.
}
console.log(WordCount("Random String"));
(text.split(/\b/).length - 1) / 2
function countWords(str) {
var matches = str.match(/\S+/g);
return matches ? matches.length : 0;
}
var str = 'one two three four five';
str.match(/\w+/g).length;
function countWords(s){
s = s.replace(/\n/g,' '); // newlines to space
s = s.replace(/(^\s*)|(\s*$)/gi,''); // remove spaces from start + end
s = s.replace(/[ ]{2,}/gi,' '); // 2 or more spaces to 1
return s.split(' ').length;
}
function countWords(passedString){
passedString = passedString.replace(/(^\s*)|(\s*$)/gi, '');
passedString = passedString.replace(/\s\s+/g, ' ');
passedString = passedString.replace(/,/g, ' ');
passedString = passedString.replace(/;/g, ' ');
passedString = passedString.replace(/\//g, ' ');
passedString = passedString.replace(/\\/g, ' ');
passedString = passedString.replace(/{/g, ' ');
passedString = passedString.replace(/}/g, ' ');
passedString = passedString.replace(/\n/g, ' ');
passedString = passedString.replace(/\./g, ' ');
passedString = passedString.replace(/[\{\}]/g, ' ');
passedString = passedString.replace(/[\(\)]/g, ' ');
passedString = passedString.replace(/[[\]]/g, ' ');
passedString = passedString.replace(/[ ]{2,}/gi, ' ');
var countWordsBySpaces = passedString.split(' ').length;
return countWordsBySpaces;
$(this).val()
.replace(/(( )|(<[^>]*>))+/g, '') // remove html spaces and tags
.replace(/\s+/g, ' ') // merge multiple spaces into one
.trim() // trim ending and beginning spaces (yes, this is needed)
.match(/\s/g) // find all spaces by regex
.length // get amount of matches
function countWords(str) {
var regEx = /([^\u0000-\u007F]|\w)+/g;
return str.match(regEx).length;
}
let leng = yourString.split(' ').filter(a => a.trim().length > 0).length
function totalWordCount() {
var str ="My life is happy"
var totalSoFar = 0;
for (var i = 0; i < str.length; i++)
if (str[i] === " ") {
totalSoFar = totalSoFar+1;
}
totalSoFar = totalSoFar+ 1;
return totalSoFar
}
console.log(totalWordCount());
let randomString = "Random String";
let stringWords = randomString.split(' ');
console.log(stringWords.length);
function wordCount(str) {
var stringArray = str.split(' ');
var count = 0;
for (var i = 0; i < stringArray.length; i++) {
var word = stringArray[i];
if (/[A-Za-z]/.test(word)) {
count++
}
}
return count
}
var str = "testing strings here's a string --.. ? // ... random characters ,,, end of string";
wordCount(str)
var quote = `Of all the talents bestowed upon men,
none is so precious as the gift of oratory.
He who enjoys it wields a power more durable than that of a great king.
He is an independent force in the world.
Abandoned by his party, betrayed by his friends, stripped of his offices,
whoever can command this power is still formidable.`;
function wordCount(text = '') {
const words = text.trim().split(/\s+/g);
if (!words[0].length) {
return 0;
}
return words.length;
};
console.log(wordCount(quote));//59
console.log(wordCount('f'));//1
console.log(wordCount(' f '));//1
console.log(wordCount(' '));//0
function WordCount(str) {
var totalSoFar = 0;
for (var i = 1; i < str.length; i++) {
if (str[i] === " ") {
totalSoFar ++;
}
}
return totalSoFar;
}
console.log(WordCount("hi my name is raj));
function countWholeWords(text, keyword) {
const times = text.match(new RegExp(`\\b${keyword}\\b`, 'gi'));
if (times) {
console.log(`${keyword} occurs ${times.length} times`);
} else {
console.log(keyword + " does not occurs")
}
}
const text = `
In a professional context it often happens that private or corporate clients corder a publication to be
made and presented with the actual content still not being ready. Think of a news blog that's
filled with content hourly on the day of going live. However, reviewers tend to be distracted
by comprehensible content, say, a random text copied from a newspaper or the internet.
`
const wordsYouAreLookingFor = ["random", "cat", "content", "reviewers", "dog", "with"]
wordsYouAreLookingFor.forEach((keyword) => countWholeWords(text, keyword));
// random occurs 1 times
// cat does not occurs
// content occurs 3 times
// reviewers occurs 1 times
// dog does not occurs
// with occurs 2 times
const TextArea = document.querySelector('textarea');
const CountContainer = document.querySelector('#demo');
TextArea.addEventListener('keypress', () => {
let TextValue = TextArea.value.split(' ').join('-').split('\n').join('-').split('-');
let WordCountArray = TextValue.filter(el => {
return el != '';
});
let WordSen = WordCountArray.length <= 1 ? 'Word' : 'Words';
console.log(WordCountArray);
CountContainer.textContent = WordCountArray.length + ' ' + WordSen;
});
TextArea.addEventListener('keyup', function () {
if (this.value === '') CountContainer.textContent = '0 Word';
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<textarea cols="30" rows="10"></textarea>
<div id="demo"></div>
<script src="app.js"></script>
</body>
</html>
export const countWords = (str: string) => {
str = str.trim();
if (!str.length) {
return str.length
}
return str.trim().split(/\s+/).length;
}
test("countwords", () => {
expect(countWords(' ')).toBe(0)
expect(countWords('78 7 ')).toBe(2)
expect(countWords('78 7 ')).toBe(2)
expect(countWords('aa, , 7')).toBe(3)
expect(countWords('aa, , \n \n \t 7 \n 4')).toBe(4)
});
var str = "Lorem ipsum dolor sit amet consectetur adipisicing elit. Labore illum fuga magni exercitationem porro? Eaque tenetur tempora nesciunt laborum deleniti, quidem nemo consequuntur voluptate alias ad soluta, molestiae, voluptas libero!" ;
let count = (str.match(/\s/g) || []).length;
console.log(count + 1 );
countWords =(str )=>{
let count = ( str.match(/\s/g) || [] ).length;
count = (count == 0 ) ? 0 : count +1 ;
return count
}