Ad

JavaScript Regex Split Including All Chars

- 1 answer

I have a string hello {user.info}! I am a {user.me} and I need to split it:

[
   "hello ",
   "{user.info}", 
   "! I am a ", 
   "{user.me}"
]

I tried to make let splited = str.split(/\{(.*?)\}/g); but I got only

[
   "hello " ,
   "user.info" ,
   "! i am " ,
   "user.me" ,
   ""
] 

without brackets

How do I do that?

Ad

Answer

Here is a version that works in case you want to keep the curly brackets:

let data = `hello {user.info}! I am a {user.me}`
data = data.split(/(?<=})|(?=\{)/);
console.log(data)

Ad
source: stackoverflow.com
Ad