简体   繁体   中英

Alternative to lookbehind in js

I am trying to use javascript to do text replacements for variables with the follow format @variable (yes I know it is bad practice, but sadly it's data from an external system so I cannot change it).

The problem is that I need to ensure that it also works if there are mail addresses in the text. Therefor it needs to match @variable but not test@example.com. If it was in another language I would simply use something like, but js does not support lookbehind.

text.replace(/(?<!\w)@[\w]+/g, replacement);

'@var' matches @var

'@var bar' matches @var

'bar@var' does not match

'bar2@var' does not match

Any javascript way of doing this using regex?

Here is an example of the expected result using negative lookbehind https://regex101.com/r/orCEGE/1

It's not entirely clear what exactly you want to replace, but here's a fairly generic method:

 const text = "@A foo@bar@baz @var@asdf.@Z"; const result = text.replace(/@(\\w+)/g, (m0, m1, pos, str) => { if (pos > 0 && /\\w/.test(str.charAt(pos-1))) { return m0; } return "{replacement for " + m1 + "}"; } ); console.log(result); 

The replacement function gets not just the matched parts of the string, but also the position where the match occurred. This match position can be used to make further decisions (eg whether the matched string should be returned unchanged (as in return m0; )).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM