3

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?

1 Answer 1

2
(^|[^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);
Sign up to request clarification or add additional context in comments.

2 Comments

Oh, it works fine. Thank you! I used: var re = new RegExp("(^|[^a-zA-Z0-9.])left(?![a-zA-Z0-9])", "gi");
@Martin regex101.com/r/tJ2mW5/25 its working fine here.see .The one you proposed will not replace leftContent

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.