2

I have something like this:

var myString = "Paul, Paula, Pauline";
var myRegExp = /Paula?/g;
var change= myString.replace(myRegExp, "George");
document.write(change);

How can I change only Paul and Paula without changing Pauline into Georgeine. Now, I get George, George, Georgeine, and I want George, George, Pauline.

0

2 Answers 2

4

You can use the following regex:

var myRegExp = /\bPaula?\b/g;

var myString = "Paul, Paula, Pauline";
var myRegExp = /\bPaula?\b/g;

var change= myString.replace(myRegExp, "George");

document.write(change);

Word boundaries (\b) are necessary as we need to tell the regex engine to fail the match if there are other word characters other Paul or Paula.

Regular expression visualization

Debuggex Demo

Sign up to request clarification or add additional context in comments.

2 Comments

Glad to help. Please consider upvoting my answer if it proved helpful and accepting since it works for you.
Actually, sometimes, debuggex.com is even more appealing than regex101.com, due to visualization. But it is true that regex101.com is much more helpful since it offers code generation and debugging (shows how the regex actually works). However, for demo purposes, I am relying on SO snippet functionality. See how your question looks now :)
1
var myRegExp = /(^|\s)Paula?(?=[,\s]|$)/g

You can use this and replace by var change= myString.replace(myRegExp, "$1George");

See demo.

https://regex101.com/r/fX3oF6/11

1 Comment

@PiotrX do accept an answer which helped you the most and upvote others which helped you

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.