0

I need to put the words of a text area into a JavaScript array. I've got it working right up to the crucial point. I've written a function to count the words, but that didn't really help as I need to count the words by using array.length or whatever the property may be.

<html>
  <head>
    <title>My Test Form</title>
  </head>

  <body>
    <textarea cols="80" rows="15"  id="words" name="words">
    </textarea>
    <br/> 
    <br/> 
    <br/> 
    <br/> 

    <script>
        function get_words()
        {
            var x = document.getElementById("words").value;
            return x;
        }

        function put_words_into_array() 
        {
            var w = get_words(); 
            var a = /// need code here to put words of the string into array
        }
    </script>
  </body>
</html>
Sumner Evans
  • 8,951
  • 5
  • 30
  • 47
upthere
  • 49
  • 1
  • 6

5 Answers5

2

You could split it on groups of nonword characters:

var a = w.split(/\W+/);
Paul
  • 139,544
  • 27
  • 275
  • 264
1

Use the split function:

function get_words() {
    var x = document.getElementById("words").value;
    return x.split(' '); // Returns an array with each word.
}
Sumner Evans
  • 8,951
  • 5
  • 30
  • 47
1

As mentioned above, use the split function.

function to_array()
{
    var words = document.getElementById('words').value;
    var words_arr = words.split(' '); // here is the array
    alert(words_arr);
}

Here is a working example: http://jsfiddle.net/X5x6P/1/

turing_machine
  • 473
  • 3
  • 13
0
function get_words(){
     var str = document.getElementById("words").value;
     return str.split(" ");
}

alert(get_words().length);
124
  • 2,757
  • 26
  • 37
0

Use the JavaScript "split" command:

var a = "1 2 3".split(" ");

This will result in the array a, having this content: ["1", "2", "3"] And keep in mind that the split function interprets it's parameter as a regular expression, when you use different separators.

Sascha Wedler
  • 395
  • 3
  • 7