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>
3

5 Answers 5

2

You could split it on groups of nonword characters:

var a = w.split(/\W+/);
Sign up to request clarification or add additional context in comments.

Comments

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/

Comments

1

Use the split function:

function get_words() {
    var x = document.getElementById("words").value;
    return x.split(' '); // Returns an array with each word.
}

Comments

0
function get_words(){
     var str = document.getElementById("words").value;
     return str.split(" ");
}

alert(get_words().length);

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.