Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx: Replace string between two non-matching strings

i want to replace a word in a string:

Input: "left.position.left = leftContent.left.posleft"

Output: "a.position.left = content.left.posleft"

Before "left" there shouldn´t be [a-zA-Z0-9.] and behind there shouldn´t be [a-zA-Z0-9].

This is my code I wrote so far:

"left.position.left = leftContent.left.posleft".replace(new RegExp("left(?![a-zA-Z0-9])", "g"), "a")

But it returns:

"a.position.a = leftContent.a.posa"

Could anybody help me?

like image 520
Martin Avatar asked Jan 02 '26 04:01

Martin


1 Answers

(^|[^a-zA-Z0-9.])left

Try this.See demo.Replace by $1a.

https://regex101.com/r/tJ2mW5/24

var re = /(^|[^a-zA-Z0-9.])left/gi;
var str = 'left.position.left = leftContent.left.posleft';
var subst = '$1a';

var result = str.replace(re, subst);
like image 112
vks Avatar answered Jan 03 '26 17:01

vks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!