Javascript逐行分隔字符串推送到数组中



我有一个多行的字符串。

one
two
three

我需要将它们添加到以行分隔的数组中

我该怎么做?

您可以使用string.split在换行符处剪切字符串。您可以添加Array.filter以删除空行。

Filter将在每string循环并创建一个新数组。如果string为空,则不会将其推送到新数组。

const str = `one
two
three`;
const ret = str.split('n').filter(x => x.length);
console.log(str);
console.log(ret);

您可以使用 String.prototype.split((,如下所示

const someString = `one
two
three`;
const myArray = someString.split('n');
console.log(myArray);

最新更新