简体   繁体   English

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

[英]javaScript - splitting string in array that matches pattern

I have got for following string as an example 我以以下字符串为例

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

I would like to have an array like this: 我想要一个像这样的数组:

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

Is this possible in with native functions? 使用本机函数可以做到这一点吗? or do i have to make a workaround? 还是我必须采取解决方法?

You could adapt the answer of Split around curly braces with search for more curly brackets and inside with any characters except a closing curly bracket 您可以在大括号周围使用“ 拆分”答案 ,以搜索更多的大括号,并在其中使用除封闭大括号之外的任何字符

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

You can use .match() with RegExp /[{]+[^}]+[}]+|[\\w\\s]+/g 您可以将.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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM