javaScript - 在与数组匹配的数组中拆分字符串

时间:2017-09-30 15:28:07

标签: javascript arrays regex

我有以下字符串为例

hello {{salutation}} {{ name }} we are glad to tell you {{ message }}

我想有一个像这样的数组:

["hello", "{{salutation}}", "{{ name }}", "we are glad to tell you", "{{ message }}"]

这是否可以使用本机功能?或者我必须做一个解决方法吗?

2 个答案:

答案 0 :(得分:2)

您可以调整answerSplit around curly braces以搜索更大的大括号,并在内部添加任何字符,但大括号

除外

var string = 'hello {{salutation}} {{ name }} we are glad to tell you {{ message }}',
    array = string.split(/\s*(\{\{[^}]+}})\s*/).filter(Boolean);
    
console.log(array);

答案 1 :(得分:0)

您可以将.match()RegExp /[{]+[^}]+[}]+|[\w\s]+/g

一起使用

var str = "hello {{salutation}} {{ name }} we are glad to tell you {{ message }}";

var res = str.match(/[{]+[^}]+[}]+|[\w\s]+/g);

console.log(res);

相关问题