4

I would like to replace all ONLY single equal signs.

var mystr = 'ONE == TWO ... THREE==FOUR ... FIVE = SIX ... SEVEN=EIGHT' ... NINE := TEN;
return mystr.replace(/(?=\=)([=]{1})(?!\=)/gm, '==');

I get the following:

ONE === TWO ... THREE===FOUR ... FIVE == SIX ... SEVEN==EIGHT ... NINE :== TEN

Numbers 5-6, 7-8, are ok. But, I would like this:

ONE == TWO ... THREE==FOUR ... FIVE == SIX ... SEVEN==EIGHT ... NINE := TEN

Whats wrong with my regex?

2
  • 1
    Your regex does nothing to try and recognize the :. So, how could it possibly know not to duplicate the last = character? (Hint: since JavaScript doesn't have lookbehind assertions this is pretty tricky... the easiest way would be a second pass to replace :== with :=.) Commented Jun 12, 2013 at 13:43
  • FYI, ([=]{1}) is the same as ([=]) is the same as (=) (parenthesis are not even needed here). Don't make it overly complicated. Commented Jun 12, 2013 at 13:47

2 Answers 2

4

Since Javascript doesn't support lookbehind assertions you can't check if the char before is an equal char or not. But you could match it an insert it again.

return mystr.replace(/([^=:])=(?!=)/g, '$1==');

See it here on Regexr.

([^=:]) is a negated character class, that matches any char, but = and : . This char is reinserted in the replacement string by the $1.

This would not work, when the first char in the string is a single "=", since the start of the string would not be matched by [^=:].

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

Comments

2

You could perhaps use this regex:

([^=:])=(?!=)

So this will match something that starts with anything not being = or : and then an = sign and no = after.

Then use a replace of $1==.

Tested here

And if you want a picture too...

Regular expression image

Comments

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.