簡體   English   中英

javaScript-在匹配模式的數組中拆分字符串

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

我以以下字符串為例

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

我想要一個像這樣的數組:

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

使用本機函數可以做到這一點嗎? 還是我必須采取解決方法?

您可以在大括號周圍使用“ 拆分”答案 ,以搜索更多的大括號,並在其中使用除封閉大括號之外的任何字符

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

您可以將.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