-2

I want to do a split by "{" and keep the "{".

The result should be an array:

[
"{  \""text\" : \"alinea 1\", \"type\" : \"paragraph\"  }",
"{  \""text\" : \"alinea 2\", \"type\" : \"paragraph\"  }"
]

The code I have got so far:

("{    \"text\": \"alinea 1\",    \"type\": \"paragraph\"  },  {    \"text\": \"alinea2\",    \"type\": \"paragraph\"  }").split(/([?={?>={]+)/g)

But the output is not as expected:

enter image description here

I am not a hero with regex... and tried to fiddle a bit with this: Javascript and regex: split string and keep the separator

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
poashoas
  • 1,790
  • 2
  • 21
  • 44
  • 2
    It would be easier to encode things the way you want rather than trying to post-process encoded strings. – gog Nov 20 '22 at 21:15
  • 1
    I agree with @gog. Where are you getting this data from? Can't you just use regular JSON? An easier way might be to make it JSON. For example, `JSON.parse("[" + str + "]")` – blex Nov 20 '22 at 21:18
  • 1
    Obvious question here is: "Why?" You're using JavaScript and trying to manipulate JSON without using the native JSON handling you have available. – Tibrogargan Nov 20 '22 at 21:18

2 Answers2

0

Please fix on server or wrap in [] before using JSON.parse to get what I expect you actually wanted

const str = `{    \"text\": \"alinea 1\",    \"type\": \"paragraph\"  },  {    \"text\": \"alinea2\",    \"type\": \"paragraph\"  }`
console.log(JSON.parse(`[${str}]`))
mplungjan
  • 169,008
  • 28
  • 173
  • 236
0

Obviously in a production situation you probably want to use native JSON operations but as an exercise you could do something like this, which seems pretty close to what you were asking for. (Note that the positive lookahead used here is pretty terrible, since it happily matches an empty string. Change the ,? to (?:(,|$)) to make it arguably less terrible)

NOTE: JSON is not a regular language. Using regular expressions to parse it is asking for a visit from Zalgo.

input = "{    \"text\": \"alinea 1\",    \"type\": \"paragraph\"  },  {    \"text\": \"alinea2\",    \"type\": \"paragraph\"  }"

pattern = /(?<obj>{[^}]*})(?=\s*(?:,?))/g
output = [...input.matchAll(pattern)].map( match => match.groups.obj )
console.log(output)
Tibrogargan
  • 4,508
  • 3
  • 19
  • 38