2017-10-18 40 views
0

我有分裂字符串與模式的問題。我知道我可以使用String.prototype.split來拆分字符串。但是,如果我使用它,我會失去分隔符。如何用字符串分割字符串而不丟失任何文本?

例如

const text = '{user} foo bar {time} test test'; 
const arr = text.split(/\{[a-z]*\}/) 
// arr = ["", " foo bar ", " test test"] 

我期望是["{user}", " foo bar ", "{time}", " test test"]

是否有可能實現與split

+2

使用'text.split(/(\ {[AZ] *})/)過濾器(布爾)' –

+0

你不知道。需要任何複雜的RegExp。試試這個'text.split(「」);' – Krusader

+1

@Krusader它不會工作,因爲''foo bar「'和''test test」' –

回答

2

嘗試以下匹配:

const text = '{user} foo bar {time} test test'; 
 
const arr = text.match(/\{.*?\}|\b[\w\s]+\b/g); 
 
// arr = ["", " foo bar ", " test test"] 
 

 
console.log(arr)