2

I've got a string

{'lalala'} text before \{'lalala'\} {'lalala'} text after

I want to get open bracket { but only if there is no escape char \ before.

Kind of /(?:[^\\])\{/ but it doesn't work at first statement.

mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • The typical approach is to match on `(^|[^\\])\{`, and then when replacing, put back the character before the curly. –  Apr 02 '17 at 09:12
  • Possible duplicate of [Javascript: negative lookbehind equivalent?](http://stackoverflow.com/questions/641407/javascript-negative-lookbehind-equivalent) – Neil Fenwick Apr 02 '17 at 09:15
  • Should it be possible to escape ``\`` with itself? – Ry- Apr 02 '17 at 09:19

2 Answers2

2

The typical approach is to match the non-\ preceding character (or beginning of string), and then put it back in your replacement logic.

const input = String.raw`{'lalala'} text before \{'lalala'\} {'lalala'} text after`;

function replace(str) {
  return input.replace(/(^|[^\\])\{'(\w+)'\}/g, 
    (_, chr, word) => chr + word.toUpperCase());
}

console.log(replace(input));
1

That's where ^ comes in: it anchors a piece of regex to the start of the string (or the line, in m multiline mode). Because a 'valid' opening bracket is either at the start of a string or after a non-\ character, we can use the following regex:

/(?:^|[^\\])\{/g

I added the g global flag because we want to match all 'valid' opening brackets. Example use:

console.log("{'lalala'} text before \\{'lalala'\\} {'lalala'} text after".match(/(?:^|[^\\])\{/g))

If you want to use the regex in a replace, you might want to capture the character before the bracket, as that gets replaced as well.

LarsW
  • 1,514
  • 1
  • 13
  • 25