简体   繁体   中英

How do I read a list from a textarea with Javascript?

I am trying to read in a list of words separated by spaces from a textbox with Javascript. This will eventually be in a website.

Thank you.

This should pretty much do it:

<textarea id="foo">some text here</textarea>

<script>
    var element = document.getElementById('foo');
    var wordlist = element.value.split(' ');
    // wordlist now contains 3 values: 'some', 'text' and 'here'
</script>

A more accurate way to do this is to use regular expressions to strip extra spaces first, and than use @Aron's method, otherwise, if you have something like "abcde" you will get an array with a lot of empty string elements, which I'm sure you don't want

Therefore, you should use:

<textarea id="foo">
    this is some   very     bad
    formatted text         a      
</textarea>

<script>
   var str = document.getElementById('foo').value;
   str = str.replace(/\s+/g, ' ').replace(/^\s+|\s$/g);
   var words = str.split(' ');
   // words will have exactly 7 items (the 7 words in the textarea)
</script>

The first .replace() function replaces all consecutive spaces with 1 space and the second one trims the whitespace from the start and the end of the string, making it ideal for word parsing :)

Instead of splitting by whitespaces, you can also try matching sequences of non-whitespace characters.

var words = document.getElementById('foo').value.match(/\S+/g);

Problems with the splitting method is that when there are leading or trailing whitespaces, you will get an empty element for them. For example, " hello world " would give you ["", "hello", "world", ""] .

You may strip the whitespaces before and after the text, but there is another problem: When the string is empty. For example, splitting "" will give you [""] .

Instead of finding what we don't want and split it, I think it is better to look for what we want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM