Ovolollo Ovolollo - 3 months ago 21
Javascript Question

Regex to remove words in curly braces

I'm looking for a method to remove any substring within the braces from another substring.

For example:

  • If I have the string
    "The cat is {not} mine"
    , I want a function that return
    "The cat is mine";

  • If I have
    "the glass was broken {by the dog}"
    , I want a function that return
    "The glass was broken "

I have read that it would be possible using the regexp in the
function but I don't know how to use it.


This works:

var s="The {yellow} cat is {not} mine";
s.replace(/\s?\{[^}]+\}/g, ''); // "The cat is mine"

The regular expression allows an optional leading space s?, then finds the opening literal brace \{, than searches multiple characters in the group []+ that are not a closing brace ^} - until the literal closing curly }.
All that operates with the g global flag for multiple replaces.
All gets replaced with "".

In the case you need to find <[this stuff]> delimited by <[]>:

var s = "The <[yellow]> cat is <[not]> mine";
s = s.replace(/\s*<\[[^\]\>]*\]>/g, "");
console.log( s );     // "The cat is mine"