1
<textarea id="check" cols="50" rows="20"></textarea>

<script>
var text = document.getElementById("check").value;
var lengthA = text;

    for (var i = 0; i < lengthA.length; i++) {
var space = " ";
if (lengthA[i] === space) {
    var next = lengthA[i] + 1;
    if (next === space) {
        lengthA.replace(lengthA[i], "");
       }
      }
     }

var length3 = lengthA.length - length2;
var words = length3 + 1;
</script>

Alright bois, me got a problemo! Im attempting to make a word counter through the law that each space equals a word (1:1). Im not sure why it is not working, it makes sense to me in my mind. I have attempted several alternatives and dwelled hours upon trying to fix this chunk. Thank you in advance to anyone that answers, even if it doesn't work! :)

EDIT: Regular expressions did the trick and replaced the incorrectly used for loop and if statements. Thanks

Sean
  • 767
  • 1
  • 6
  • 19
  • Since you already use the `replace` function in your solution, have you taken a look at this yet - https://stackoverflow.com/questions/1981349/regex-to-replace-multiple-spaces-with-a-single-space – BatScream Jun 19 '18 at 03:57

3 Answers3

1

How about just the below -

var text = document.getElementById("check").value.replace (/ +/g, " ");

Not sure, why you would need a for loop to begin with.

/ +/ will more than 1 space g will do all the changes throughout the text

Sudipta Mondal
  • 2,550
  • 1
  • 19
  • 20
1

To remove the duplicate space, the following code

lengthA.replace(lengthA[i], "");

should be

lengthA = lengthA.substring(0, i) + lengthA.substring(i + 1);
// i should not increase
i--;
continue;

You misunderstand the usage of replace.

Terry Wei
  • 1,521
  • 8
  • 16
1

Use str.replace() of JavaScript to do this. This will remove not only space but also work for tabs, newlines etc.

Usage:

var string = string.replace(/\s\s+/g, ' ');

So change below code:

var lengthA = text;

    for (var i = 0; i < lengthA.length; i++) {
var space = " ";
if (lengthA[i] === space) {
    var next = lengthA[i] + 1;
    if (next === space) {
        lengthA.replace(lengthA[i], "");
       }
      }
     }

To this:

var lengthA = text.replace(/\s\s+/g, ' ');

Reference here : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

Vikasdeep Singh
  • 20,983
  • 15
  • 78
  • 104