upthere
upthere

Reputation: 49

How can I put the individual words of a string in a javascript array?

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>

Upvotes: 0

Views: 3423

Answers (5)

Sascha Wedler
Sascha Wedler

Reputation: 413

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.

Upvotes: 0

turing_machine
turing_machine

Reputation: 473

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/

Upvotes: 1

NiiL
NiiL

Reputation: 2827

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

alert(get_words().length);

Upvotes: 0

Paul
Paul

Reputation: 141839

You could split it on groups of nonword characters:

var a = w.split(/\W+/);

Upvotes: 2

Sumner Evans
Sumner Evans

Reputation: 9157

Use the split function:

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

Upvotes: 1

Related Questions