Counting the words in a textarea
I've two working ways to do so, but which one should I use?
Common part: var textarea = document.getElementById("textarea");
First way:
function updateStatusBar() {
var text = textarea.value;
statusBar.value = "Words: " + (text ? text.match(/bS+b/g).length : "0") +
" Characters: " + text.replace(/s/g, "").length +
" / " + text.replace(/n/g, "").length;
}
and second way:
function updateStatusBar() {
var text = textarea.value;
statusBar.value = "Words: " + (text.split(/bS+b/).length - 1) +
" Characters: " + text.replace(/s/g, "").length +
" / " + text.replace(/n/g, "").length;
}
Please review the Words: counting code. Which one should I use?
javascript strings regex
add a comment |
I've two working ways to do so, but which one should I use?
Common part: var textarea = document.getElementById("textarea");
First way:
function updateStatusBar() {
var text = textarea.value;
statusBar.value = "Words: " + (text ? text.match(/bS+b/g).length : "0") +
" Characters: " + text.replace(/s/g, "").length +
" / " + text.replace(/n/g, "").length;
}
and second way:
function updateStatusBar() {
var text = textarea.value;
statusBar.value = "Words: " + (text.split(/bS+b/).length - 1) +
" Characters: " + text.replace(/s/g, "").length +
" / " + text.replace(/n/g, "").length;
}
Please review the Words: counting code. Which one should I use?
javascript strings regex
I would strongly recommend you, to count your characters by using something like:textarea.innerText.length
– user33722
Mar 3 '14 at 10:34
newlines aren't characters.
– annn
Mar 3 '14 at 11:05
add a comment |
I've two working ways to do so, but which one should I use?
Common part: var textarea = document.getElementById("textarea");
First way:
function updateStatusBar() {
var text = textarea.value;
statusBar.value = "Words: " + (text ? text.match(/bS+b/g).length : "0") +
" Characters: " + text.replace(/s/g, "").length +
" / " + text.replace(/n/g, "").length;
}
and second way:
function updateStatusBar() {
var text = textarea.value;
statusBar.value = "Words: " + (text.split(/bS+b/).length - 1) +
" Characters: " + text.replace(/s/g, "").length +
" / " + text.replace(/n/g, "").length;
}
Please review the Words: counting code. Which one should I use?
javascript strings regex
I've two working ways to do so, but which one should I use?
Common part: var textarea = document.getElementById("textarea");
First way:
function updateStatusBar() {
var text = textarea.value;
statusBar.value = "Words: " + (text ? text.match(/bS+b/g).length : "0") +
" Characters: " + text.replace(/s/g, "").length +
" / " + text.replace(/n/g, "").length;
}
and second way:
function updateStatusBar() {
var text = textarea.value;
statusBar.value = "Words: " + (text.split(/bS+b/).length - 1) +
" Characters: " + text.replace(/s/g, "").length +
" / " + text.replace(/n/g, "").length;
}
Please review the Words: counting code. Which one should I use?
javascript strings regex
javascript strings regex
edited Mar 3 '14 at 4:50
asked Mar 3 '14 at 4:43
annn
10215
10215
I would strongly recommend you, to count your characters by using something like:textarea.innerText.length
– user33722
Mar 3 '14 at 10:34
newlines aren't characters.
– annn
Mar 3 '14 at 11:05
add a comment |
I would strongly recommend you, to count your characters by using something like:textarea.innerText.length
– user33722
Mar 3 '14 at 10:34
newlines aren't characters.
– annn
Mar 3 '14 at 11:05
I would strongly recommend you, to count your characters by using something like:
textarea.innerText.length– user33722
Mar 3 '14 at 10:34
I would strongly recommend you, to count your characters by using something like:
textarea.innerText.length– user33722
Mar 3 '14 at 10:34
newlines aren't characters.
– annn
Mar 3 '14 at 11:05
newlines aren't characters.
– annn
Mar 3 '14 at 11:05
add a comment |
3 Answers
3
active
oldest
votes
To simplify, you are asking which of these ways is better to count the number of words in text:
text ? text.match(/bS+b/g).length : "0"
// ... versus ...
text.split(/bS+b/).length - 1
First of all, the first expression will crash for a non-empty text without words, for example :!@#$. Because a non-empty text is "true", but the .match will return null, so you'll get a null pointer exception in .length.
Second of all, a more intuitive regular expression for words is this:
text.match(/ww+/g).length
Since by its definition, w+ is a word. I added an extra w to exclude single letters, as that seems closer to what you want.
Your main question concerns the angle that if you use match you have to check for null, but if you use split you don't have to. So after corrections, we're comparing these two:
(words = text.match(/ww+/g)) == null ? 0 : words.length
// ... versus ...
text.split(/ww+/).length - 1
And since the second one is much shorter, I recommend that one. Even though matching seems more intuitive to me than splitting to solve this problem. Short is nice. And it seems you don't need the words list for anything, so there's no point whatsoever to create it.
I want a solution.returns "2 words", i.e. it don't work. See codepen.io/rhroyston/pen/ebrveB. I came up with the answer below. ...It boiled down to handling multiple spaces, tabs, and end-of-sentence characters such as a period,.
– Ron Royston
6 mins ago
add a comment |
A few comments on this...
What is a character? In your code, you are only counting non-spaces as characters. But, if the user enters a a that counts as 10 characters to me.....
From my perspective, Characters can just be text.length.
Still your definition appears to be 'non-space characters'. Using that definition....
Now, about the regex. You describe 2 ways to count words, and one way to count non-space characters, and then, for some odd reason, you count newlines as well.
So, if I were to suggest that the best way to do it was with just one big, and few small regex... ? The big regex is the most complicated to run because it needs to do more complicated matching on a larger value. By stripping the value sooner, you can make it faster.
Note, you do not need the b word boundary markers when dealing with either s+ or S+.
//Function declaration, will be hoisted for 'addEventListener'
//Most of the work is done to have this work for multiple text area's
function updateStatus(){
var text = this.value,
// replace all words with an x
xWords = text.replace(/S+/g, "x"),
//Replace those x's
noWords = xWords.replace(/x/g, ""),
//Get rid of newlines from just the spaces.
noNewLines = noWords.replace(/n/g, "");
//You could consider a template function here..
statusBar.textContent = "Length: " + text.length +
" Words: " + (xWords.length - noWords.length) +
" Characters: " + (text.length - noWords.length) +
" / " + (noWords.length - noNewLines.length);
}
The above creates successively smaller string values, and compares the difference in length to compute the result....
Sometimes Plan C is the better option.
With the help of Konijn we/I have put together this jsfiddle which shows it in operation.
newlineis not a character and.is not a word (put a.on a new line).
– Ron Royston
1 min ago
add a comment |
- Replace
tabandnewlineand sentence ending characters, e.g.., withspacecharacter. - Split the resulting string on
spacecharacter.
.trim()item and.pushto new array if it is not an empty string.
The .length of that new array provides your word count. See it in action here/below (test by adding several spaces between words and by using several line breaks):
var txt = document.getElementById("txt");
var resultSpan = document.getElementById("res");
txt.addEventListener('keyup', count);
function count(){
var resultArray = ;
//replace all tab, newline, periods, exclamations, question marks w space
var str = this.value.replace(/[tnr.?!]/gm,' ');
//split string by space character
var wordArray = str.split(" ");
//for each array item, remove all space characters
for (var i = 0; i < wordArray.length; i++) {
var item = wordArray[i].trim();
//if item contains characters push it into a new array
if(item.length > 0){
resultArray.push(item);
}
}
resultSpan.innerText = resultArray.length;
}<textarea id="txt" rows="8" cols="40"></textarea>
<p><span id="res">0</span> words.</p>add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
return StackExchange.using("mathjaxEditing", function () {
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
});
});
}, "mathjax-editing");
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "196"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f43274%2fcounting-the-words-in-a-textarea%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
To simplify, you are asking which of these ways is better to count the number of words in text:
text ? text.match(/bS+b/g).length : "0"
// ... versus ...
text.split(/bS+b/).length - 1
First of all, the first expression will crash for a non-empty text without words, for example :!@#$. Because a non-empty text is "true", but the .match will return null, so you'll get a null pointer exception in .length.
Second of all, a more intuitive regular expression for words is this:
text.match(/ww+/g).length
Since by its definition, w+ is a word. I added an extra w to exclude single letters, as that seems closer to what you want.
Your main question concerns the angle that if you use match you have to check for null, but if you use split you don't have to. So after corrections, we're comparing these two:
(words = text.match(/ww+/g)) == null ? 0 : words.length
// ... versus ...
text.split(/ww+/).length - 1
And since the second one is much shorter, I recommend that one. Even though matching seems more intuitive to me than splitting to solve this problem. Short is nice. And it seems you don't need the words list for anything, so there's no point whatsoever to create it.
I want a solution.returns "2 words", i.e. it don't work. See codepen.io/rhroyston/pen/ebrveB. I came up with the answer below. ...It boiled down to handling multiple spaces, tabs, and end-of-sentence characters such as a period,.
– Ron Royston
6 mins ago
add a comment |
To simplify, you are asking which of these ways is better to count the number of words in text:
text ? text.match(/bS+b/g).length : "0"
// ... versus ...
text.split(/bS+b/).length - 1
First of all, the first expression will crash for a non-empty text without words, for example :!@#$. Because a non-empty text is "true", but the .match will return null, so you'll get a null pointer exception in .length.
Second of all, a more intuitive regular expression for words is this:
text.match(/ww+/g).length
Since by its definition, w+ is a word. I added an extra w to exclude single letters, as that seems closer to what you want.
Your main question concerns the angle that if you use match you have to check for null, but if you use split you don't have to. So after corrections, we're comparing these two:
(words = text.match(/ww+/g)) == null ? 0 : words.length
// ... versus ...
text.split(/ww+/).length - 1
And since the second one is much shorter, I recommend that one. Even though matching seems more intuitive to me than splitting to solve this problem. Short is nice. And it seems you don't need the words list for anything, so there's no point whatsoever to create it.
I want a solution.returns "2 words", i.e. it don't work. See codepen.io/rhroyston/pen/ebrveB. I came up with the answer below. ...It boiled down to handling multiple spaces, tabs, and end-of-sentence characters such as a period,.
– Ron Royston
6 mins ago
add a comment |
To simplify, you are asking which of these ways is better to count the number of words in text:
text ? text.match(/bS+b/g).length : "0"
// ... versus ...
text.split(/bS+b/).length - 1
First of all, the first expression will crash for a non-empty text without words, for example :!@#$. Because a non-empty text is "true", but the .match will return null, so you'll get a null pointer exception in .length.
Second of all, a more intuitive regular expression for words is this:
text.match(/ww+/g).length
Since by its definition, w+ is a word. I added an extra w to exclude single letters, as that seems closer to what you want.
Your main question concerns the angle that if you use match you have to check for null, but if you use split you don't have to. So after corrections, we're comparing these two:
(words = text.match(/ww+/g)) == null ? 0 : words.length
// ... versus ...
text.split(/ww+/).length - 1
And since the second one is much shorter, I recommend that one. Even though matching seems more intuitive to me than splitting to solve this problem. Short is nice. And it seems you don't need the words list for anything, so there's no point whatsoever to create it.
To simplify, you are asking which of these ways is better to count the number of words in text:
text ? text.match(/bS+b/g).length : "0"
// ... versus ...
text.split(/bS+b/).length - 1
First of all, the first expression will crash for a non-empty text without words, for example :!@#$. Because a non-empty text is "true", but the .match will return null, so you'll get a null pointer exception in .length.
Second of all, a more intuitive regular expression for words is this:
text.match(/ww+/g).length
Since by its definition, w+ is a word. I added an extra w to exclude single letters, as that seems closer to what you want.
Your main question concerns the angle that if you use match you have to check for null, but if you use split you don't have to. So after corrections, we're comparing these two:
(words = text.match(/ww+/g)) == null ? 0 : words.length
// ... versus ...
text.split(/ww+/).length - 1
And since the second one is much shorter, I recommend that one. Even though matching seems more intuitive to me than splitting to solve this problem. Short is nice. And it seems you don't need the words list for anything, so there's no point whatsoever to create it.
edited Mar 3 '14 at 12:27
answered Mar 3 '14 at 6:49
janos
97.2k12125350
97.2k12125350
I want a solution.returns "2 words", i.e. it don't work. See codepen.io/rhroyston/pen/ebrveB. I came up with the answer below. ...It boiled down to handling multiple spaces, tabs, and end-of-sentence characters such as a period,.
– Ron Royston
6 mins ago
add a comment |
I want a solution.returns "2 words", i.e. it don't work. See codepen.io/rhroyston/pen/ebrveB. I came up with the answer below. ...It boiled down to handling multiple spaces, tabs, and end-of-sentence characters such as a period,.
– Ron Royston
6 mins ago
I want a solution. returns "2 words", i.e. it don't work. See codepen.io/rhroyston/pen/ebrveB. I came up with the answer below. ...It boiled down to handling multiple spaces, tabs, and end-of-sentence characters such as a period, .– Ron Royston
6 mins ago
I want a solution. returns "2 words", i.e. it don't work. See codepen.io/rhroyston/pen/ebrveB. I came up with the answer below. ...It boiled down to handling multiple spaces, tabs, and end-of-sentence characters such as a period, .– Ron Royston
6 mins ago
add a comment |
A few comments on this...
What is a character? In your code, you are only counting non-spaces as characters. But, if the user enters a a that counts as 10 characters to me.....
From my perspective, Characters can just be text.length.
Still your definition appears to be 'non-space characters'. Using that definition....
Now, about the regex. You describe 2 ways to count words, and one way to count non-space characters, and then, for some odd reason, you count newlines as well.
So, if I were to suggest that the best way to do it was with just one big, and few small regex... ? The big regex is the most complicated to run because it needs to do more complicated matching on a larger value. By stripping the value sooner, you can make it faster.
Note, you do not need the b word boundary markers when dealing with either s+ or S+.
//Function declaration, will be hoisted for 'addEventListener'
//Most of the work is done to have this work for multiple text area's
function updateStatus(){
var text = this.value,
// replace all words with an x
xWords = text.replace(/S+/g, "x"),
//Replace those x's
noWords = xWords.replace(/x/g, ""),
//Get rid of newlines from just the spaces.
noNewLines = noWords.replace(/n/g, "");
//You could consider a template function here..
statusBar.textContent = "Length: " + text.length +
" Words: " + (xWords.length - noWords.length) +
" Characters: " + (text.length - noWords.length) +
" / " + (noWords.length - noNewLines.length);
}
The above creates successively smaller string values, and compares the difference in length to compute the result....
Sometimes Plan C is the better option.
With the help of Konijn we/I have put together this jsfiddle which shows it in operation.
newlineis not a character and.is not a word (put a.on a new line).
– Ron Royston
1 min ago
add a comment |
A few comments on this...
What is a character? In your code, you are only counting non-spaces as characters. But, if the user enters a a that counts as 10 characters to me.....
From my perspective, Characters can just be text.length.
Still your definition appears to be 'non-space characters'. Using that definition....
Now, about the regex. You describe 2 ways to count words, and one way to count non-space characters, and then, for some odd reason, you count newlines as well.
So, if I were to suggest that the best way to do it was with just one big, and few small regex... ? The big regex is the most complicated to run because it needs to do more complicated matching on a larger value. By stripping the value sooner, you can make it faster.
Note, you do not need the b word boundary markers when dealing with either s+ or S+.
//Function declaration, will be hoisted for 'addEventListener'
//Most of the work is done to have this work for multiple text area's
function updateStatus(){
var text = this.value,
// replace all words with an x
xWords = text.replace(/S+/g, "x"),
//Replace those x's
noWords = xWords.replace(/x/g, ""),
//Get rid of newlines from just the spaces.
noNewLines = noWords.replace(/n/g, "");
//You could consider a template function here..
statusBar.textContent = "Length: " + text.length +
" Words: " + (xWords.length - noWords.length) +
" Characters: " + (text.length - noWords.length) +
" / " + (noWords.length - noNewLines.length);
}
The above creates successively smaller string values, and compares the difference in length to compute the result....
Sometimes Plan C is the better option.
With the help of Konijn we/I have put together this jsfiddle which shows it in operation.
newlineis not a character and.is not a word (put a.on a new line).
– Ron Royston
1 min ago
add a comment |
A few comments on this...
What is a character? In your code, you are only counting non-spaces as characters. But, if the user enters a a that counts as 10 characters to me.....
From my perspective, Characters can just be text.length.
Still your definition appears to be 'non-space characters'. Using that definition....
Now, about the regex. You describe 2 ways to count words, and one way to count non-space characters, and then, for some odd reason, you count newlines as well.
So, if I were to suggest that the best way to do it was with just one big, and few small regex... ? The big regex is the most complicated to run because it needs to do more complicated matching on a larger value. By stripping the value sooner, you can make it faster.
Note, you do not need the b word boundary markers when dealing with either s+ or S+.
//Function declaration, will be hoisted for 'addEventListener'
//Most of the work is done to have this work for multiple text area's
function updateStatus(){
var text = this.value,
// replace all words with an x
xWords = text.replace(/S+/g, "x"),
//Replace those x's
noWords = xWords.replace(/x/g, ""),
//Get rid of newlines from just the spaces.
noNewLines = noWords.replace(/n/g, "");
//You could consider a template function here..
statusBar.textContent = "Length: " + text.length +
" Words: " + (xWords.length - noWords.length) +
" Characters: " + (text.length - noWords.length) +
" / " + (noWords.length - noNewLines.length);
}
The above creates successively smaller string values, and compares the difference in length to compute the result....
Sometimes Plan C is the better option.
With the help of Konijn we/I have put together this jsfiddle which shows it in operation.
A few comments on this...
What is a character? In your code, you are only counting non-spaces as characters. But, if the user enters a a that counts as 10 characters to me.....
From my perspective, Characters can just be text.length.
Still your definition appears to be 'non-space characters'. Using that definition....
Now, about the regex. You describe 2 ways to count words, and one way to count non-space characters, and then, for some odd reason, you count newlines as well.
So, if I were to suggest that the best way to do it was with just one big, and few small regex... ? The big regex is the most complicated to run because it needs to do more complicated matching on a larger value. By stripping the value sooner, you can make it faster.
Note, you do not need the b word boundary markers when dealing with either s+ or S+.
//Function declaration, will be hoisted for 'addEventListener'
//Most of the work is done to have this work for multiple text area's
function updateStatus(){
var text = this.value,
// replace all words with an x
xWords = text.replace(/S+/g, "x"),
//Replace those x's
noWords = xWords.replace(/x/g, ""),
//Get rid of newlines from just the spaces.
noNewLines = noWords.replace(/n/g, "");
//You could consider a template function here..
statusBar.textContent = "Length: " + text.length +
" Words: " + (xWords.length - noWords.length) +
" Characters: " + (text.length - noWords.length) +
" / " + (noWords.length - noNewLines.length);
}
The above creates successively smaller string values, and compares the difference in length to compute the result....
Sometimes Plan C is the better option.
With the help of Konijn we/I have put together this jsfiddle which shows it in operation.
edited Mar 4 '14 at 17:58
answered Mar 3 '14 at 5:40
rolfl♦
90.7k13190394
90.7k13190394
newlineis not a character and.is not a word (put a.on a new line).
– Ron Royston
1 min ago
add a comment |
newlineis not a character and.is not a word (put a.on a new line).
– Ron Royston
1 min ago
newline is not a character and . is not a word (put a . on a new line).– Ron Royston
1 min ago
newline is not a character and . is not a word (put a . on a new line).– Ron Royston
1 min ago
add a comment |
- Replace
tabandnewlineand sentence ending characters, e.g.., withspacecharacter. - Split the resulting string on
spacecharacter.
.trim()item and.pushto new array if it is not an empty string.
The .length of that new array provides your word count. See it in action here/below (test by adding several spaces between words and by using several line breaks):
var txt = document.getElementById("txt");
var resultSpan = document.getElementById("res");
txt.addEventListener('keyup', count);
function count(){
var resultArray = ;
//replace all tab, newline, periods, exclamations, question marks w space
var str = this.value.replace(/[tnr.?!]/gm,' ');
//split string by space character
var wordArray = str.split(" ");
//for each array item, remove all space characters
for (var i = 0; i < wordArray.length; i++) {
var item = wordArray[i].trim();
//if item contains characters push it into a new array
if(item.length > 0){
resultArray.push(item);
}
}
resultSpan.innerText = resultArray.length;
}<textarea id="txt" rows="8" cols="40"></textarea>
<p><span id="res">0</span> words.</p>add a comment |
- Replace
tabandnewlineand sentence ending characters, e.g.., withspacecharacter. - Split the resulting string on
spacecharacter.
.trim()item and.pushto new array if it is not an empty string.
The .length of that new array provides your word count. See it in action here/below (test by adding several spaces between words and by using several line breaks):
var txt = document.getElementById("txt");
var resultSpan = document.getElementById("res");
txt.addEventListener('keyup', count);
function count(){
var resultArray = ;
//replace all tab, newline, periods, exclamations, question marks w space
var str = this.value.replace(/[tnr.?!]/gm,' ');
//split string by space character
var wordArray = str.split(" ");
//for each array item, remove all space characters
for (var i = 0; i < wordArray.length; i++) {
var item = wordArray[i].trim();
//if item contains characters push it into a new array
if(item.length > 0){
resultArray.push(item);
}
}
resultSpan.innerText = resultArray.length;
}<textarea id="txt" rows="8" cols="40"></textarea>
<p><span id="res">0</span> words.</p>add a comment |
- Replace
tabandnewlineand sentence ending characters, e.g.., withspacecharacter. - Split the resulting string on
spacecharacter.
.trim()item and.pushto new array if it is not an empty string.
The .length of that new array provides your word count. See it in action here/below (test by adding several spaces between words and by using several line breaks):
var txt = document.getElementById("txt");
var resultSpan = document.getElementById("res");
txt.addEventListener('keyup', count);
function count(){
var resultArray = ;
//replace all tab, newline, periods, exclamations, question marks w space
var str = this.value.replace(/[tnr.?!]/gm,' ');
//split string by space character
var wordArray = str.split(" ");
//for each array item, remove all space characters
for (var i = 0; i < wordArray.length; i++) {
var item = wordArray[i].trim();
//if item contains characters push it into a new array
if(item.length > 0){
resultArray.push(item);
}
}
resultSpan.innerText = resultArray.length;
}<textarea id="txt" rows="8" cols="40"></textarea>
<p><span id="res">0</span> words.</p>- Replace
tabandnewlineand sentence ending characters, e.g.., withspacecharacter. - Split the resulting string on
spacecharacter.
.trim()item and.pushto new array if it is not an empty string.
The .length of that new array provides your word count. See it in action here/below (test by adding several spaces between words and by using several line breaks):
var txt = document.getElementById("txt");
var resultSpan = document.getElementById("res");
txt.addEventListener('keyup', count);
function count(){
var resultArray = ;
//replace all tab, newline, periods, exclamations, question marks w space
var str = this.value.replace(/[tnr.?!]/gm,' ');
//split string by space character
var wordArray = str.split(" ");
//for each array item, remove all space characters
for (var i = 0; i < wordArray.length; i++) {
var item = wordArray[i].trim();
//if item contains characters push it into a new array
if(item.length > 0){
resultArray.push(item);
}
}
resultSpan.innerText = resultArray.length;
}<textarea id="txt" rows="8" cols="40"></textarea>
<p><span id="res">0</span> words.</p>var txt = document.getElementById("txt");
var resultSpan = document.getElementById("res");
txt.addEventListener('keyup', count);
function count(){
var resultArray = ;
//replace all tab, newline, periods, exclamations, question marks w space
var str = this.value.replace(/[tnr.?!]/gm,' ');
//split string by space character
var wordArray = str.split(" ");
//for each array item, remove all space characters
for (var i = 0; i < wordArray.length; i++) {
var item = wordArray[i].trim();
//if item contains characters push it into a new array
if(item.length > 0){
resultArray.push(item);
}
}
resultSpan.innerText = resultArray.length;
}<textarea id="txt" rows="8" cols="40"></textarea>
<p><span id="res">0</span> words.</p>var txt = document.getElementById("txt");
var resultSpan = document.getElementById("res");
txt.addEventListener('keyup', count);
function count(){
var resultArray = ;
//replace all tab, newline, periods, exclamations, question marks w space
var str = this.value.replace(/[tnr.?!]/gm,' ');
//split string by space character
var wordArray = str.split(" ");
//for each array item, remove all space characters
for (var i = 0; i < wordArray.length; i++) {
var item = wordArray[i].trim();
//if item contains characters push it into a new array
if(item.length > 0){
resultArray.push(item);
}
}
resultSpan.innerText = resultArray.length;
}<textarea id="txt" rows="8" cols="40"></textarea>
<p><span id="res">0</span> words.</p>edited 14 mins ago
answered 20 mins ago
Ron Royston
1315
1315
add a comment |
add a comment |
Thanks for contributing an answer to Code Review Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
Use MathJax to format equations. MathJax reference.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f43274%2fcounting-the-words-in-a-textarea%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
I would strongly recommend you, to count your characters by using something like:
textarea.innerText.length– user33722
Mar 3 '14 at 10:34
newlines aren't characters.
– annn
Mar 3 '14 at 11:05