Remove all text, character before first bracket and after last bracket

My string :

var string = '.,.a,,{Correct Answer Nr.1 : b.) Susan },{Correct Answer Nr.3 : b.) She doesn’t say },.x.b,'

How can i remove all text, character before first { and after last }?

My desired result :

{Correct Answer Nr.1 : b.) Susan },{Correct Answer Nr.3 : b.) She doesn’t say }

and remove : .,.a,, and ,.x.b,

Thank you

>Solution :

We can try the following regex replacement:

var string = '.,.a,,{Correct Answer Nr.1 : b.) Susan },{Correct Answer Nr.3 : b.) She doesn’t say },.x.b,';
var output = string.replace(/^[^{]+|[^}]+$/g, "");
console.log(output);

The regex pattern used here says to match:

  • ^ from the start of the string
  • [^{]+ match one or more leading characters which are not {
  • | OR
  • [^}]+ match one or more trailing characters which are not }
  • $ at the end of the string

Leave a Reply