How to replace all substrings except which are in curly braces using regexp?

Viewed 179

I need to replace all substrings except those which are in curly braces. For example, from such string:

let str = 'some text one some text one some text {one} some text';

I need to get the following string:

str = 'some text two some text two some text {one} some text';

I tried this:

console.log(str.replace(/one(?!\{one\})/g, 'two'));

but got this:

some text two some text two some text {two} some text

How to do it?

3 Answers

Capture the character before and after, if they are not { and }:

str.replace(/([^\{])one([^\}])/g, '$1two$2')

A basic version of matching would be to use matching whitespace, begin or end. This way it also doesn't capture inside "cones". Which you might or might not want, that's unclear in the question.

(^|\s)one(\s|$)

let str = 'some text one some text one some text {one} some text';
str.replace(/(^|\s)one(\s|$)/gm, '$1two$2');
console.log(str);

In more complex texts, you need to take into account a lot more. E.g. periods and comma's.

Change your regex to this,

(^|[^{])one(?!\})

and replace it with $1two

Demo

Here is javascipt sample code,

let str = 'some text one some text one some text {one} some text';
console.log(str.replace(/(^|[^{])one(?!\})/g, '$1two'));

This prints following output,

some text two some text two some text {one} some text
Related