Convert word list into array [closed]

橙三吉。 提交于 2019-12-11 07:17:18

问题


I've tried to see if there were any scripts to convert a list of words into an array and I can't seem to find one.

Anyone know where I can find one?

Input:

Dog
Cat
Hamster

Gets converted to

["Dog", "Cat", "Hamster"]

Noo.. this isn't what I mean. I have a txt file with a bunch of words on each line and I was wondering if there was something out there already created that can convert each word into an array.


回答1:


Just use split on the string.

For example:

var textarea = document.getElementById('list');
var arr = [];
textarea.addEventListener('input', function () {
    arr = this.value.split('\n');
    console.log(arr);
}, false);

Demo




回答2:


If the string is actually "Dog\nCat\nHamster" then just do

"Dog\nCat\nHamster".split('\n');//returns ["Dog", "Cat", "Hamster"]

For a TextArea try this

myTextArea.value.split('\n'); // it will return desired output.

Where myTextArea is the TextArea you can get using getElement.




回答3:


I think the best solution for a textarea input is using the match() function of javascript like this:

var words = []
$('textarea').on('blur', function(){
    words = $(this).val().match(/\w+/g)
    alert(words)
})

here a fiddle of it working.

This doesn't need for the words to be in different lines.



来源:https://stackoverflow.com/questions/25076300/convert-word-list-into-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!