How to find char if there is not another one before

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.

Answer

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

Leave a Reply

Your email address will not be published. Required fields are marked *