2017-10-18 74 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)