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.
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.
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));
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.