开发者

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 "a b c d e" 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜