Reputation:
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?
Upvotes: 2
Views: 285
Reputation: 1497
Capture the character before and after, if they are not {
and }
:
str.replace(/([^\{])one([^\}])/g, '$1two$2')
Upvotes: 5
Reputation: 6176
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.
Upvotes: 1
Reputation: 18357
Change your regex to this,
(^|[^{])one(?!\})
and replace it with $1two
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
Upvotes: 1