Search code examples
javascriptregexdoublequote

regEx to match all double quotes wrapped in brackets


Looking for some help on this one. I need to match all double quotes between {} brackets. Then I will escape these double quotes.

(37, "2012 Fall", null, null, 0, 1, "1420", {"canDelete":false, "cantDeleteModes":[2, 3, 5]}, "2020-05-28T18:06:48.000Z", "2020-10-27T19:42:03.000Z", 1, 1);

Here is the reqex I have so far...

/(?<=\{).*?(?=\})/g

but that matches everything between the {} brackets.

Expected output...

(37, "2012 Fall", null, null, 0, 1, "1420", {\"canDelete\":false, \"cantDeleteModes\":[2, 3, 5]}, "2020-05-28T18:06:48.000Z", "2020-10-27T19:42:03.000Z", 1, 1);

Any help would be appreciated ;=)


Solution

  • This code should get you going:

    const input = `(37, "2012 Fall", null, null, 0, 1, "1420", {"canDelete":false, "cantDeleteModes":[2, 3, 5]}, "2020-05-28T18:06:48.000Z", "2020-10-27T19:42:03.000Z", 1, 1);`
    
    const regex = /{(.*)}/
    
    const substr = input.match(regex)[1]
    const replacement = substr.replaceAll('"', '\\"')
    
    const result = input.replace(substr, replacement)
    
    console.log(result)

    Explanation

    • /{(.*)}/ matches everything between brackets {} non-lazily
    • input.match(regex)[1] - returns the string of the first match

    Remarks:
    It was the easiest solution for me to write and to understand. If you need something more performant, one possible way of going about it would be to iterate over the chars of the string, be aware of any {} brackets and replace the quotes only when an opening bracket but no closing bracket was seen before (and keep track of multiple opening and closing brackets so to note the beginning. So you'd need some kind of "level"-counter which increases and decreases depending on the occurrence of opening and closing brackets).