Javascript 如何使用模式拆分字符串而不丢失任何文本?

Javascript 如何使用模式拆分字符串而不丢失任何文本?,javascript,regex,string,Javascript,Regex,String,我无法用模式拆分字符串。我知道我可以使用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”] 是否可以通

我无法用模式拆分字符串。我知道我可以使用
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”]


是否可以通过
拆分实现?

尝试以下匹配:

const text='{user}foo bar{time}test';
const arr=text.match(/\{.*\}\b[\w\s]+\b/g);
//arr=[“”、“foo-bar”、“test-test”]

console.log(arr)
尝试以下匹配:

const text='{user}foo bar{time}test';
const arr=text.match(/\{.*\}\b[\w\s]+\b/g);
//arr=[“”、“foo-bar”、“test-test”]

console.log(arr)
使用
text.split(/(\{[a-z]*})/).filter(Boolean)
您不需要任何复杂的RegExp。试试这个
text.split(“”)
@Krusader由于
“foo-bar”
“test-test”
的原因,它将无法工作,感谢@WiktorStribiżewUse
text.split(/(\{[a-z]*})/).filter(Boolean)
您不需要任何复杂的RegExp。试试这个
text.split(“”)
@Krusader由于
“foo bar”
“test test”
感谢@WiktorStribiżew的工作,它将无法工作