我如何在js中拆分数组?

时间:2017-11-16 09:25:02

标签: javascript regex

我如何在js中分割字符串以获得结果:

result = ["post_address", "location", "area"]

这是问题吗?需要帮助re

let re = ???
let arr = "post_address[location][area]".split(re)

4 个答案:

答案 0 :(得分:2)

只需按/\[|\]/拆分,然后移除空字符串

var output = "post_address[location][area]".split(/\[|\]/).filter((s)=>s.length > 0);

console.log(output);

答案 1 :(得分:0)

您可以像这样使用正则表达式:

var re = /^(\w*)\[(\w*)\]\[(\w*)\]$/gi;

答案 2 :(得分:0)

使用Lodash

const str = "post_address[location][area]";
const output = _.compact(_.split(str, /\[|\]/));
console.log(output);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.4/lodash.min.js"></script>

答案 3 :(得分:0)

有更短的方式

enter image description here

实际上与

相同
'post_address[location][area]'.split(/[^\w]+/).filter(i => i)

&#13;
&#13;
console.log(
    'post_address[location][area]'.match(/(\w+)/g)
);

console.log(
    'post_address[location][area]'.split(/[^\w]+/).filter(i => i)
);
&#13;
&#13;
&#13;