0

I'm trying to clean up a file using JavaScript. The file contains lines of text like this:

a <- b + c / d;

I want to replace all <- with = when there is a string of non-whitespace on either side of the <-, separated by a single space. Pretty easy in theory:

line = "a <- b + c / d"
result = line.replace( /(\S+) <- (\S+)/, /$1 = $2/ )

The above code produces /a = b/ + c / d when run. However, conceptually, it should produce a = b + c / d. How can I use $1-style backreferences without allowing JavaScript the opportunity to insert slashes willy-nilly?

2 Answers 2

3

Use a string for the second parameter:

result = line.replace( /(\S+) <- (\S+)/, "$1 = $2" );.

What is happening is the second parameter is being coerced from a RegExp to a String which adds the slashes in the replacement.

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

Comments

0

2nd parameter of replace is not regex but String.

You need to use it like this:

result  = line.replace( /(\S+) <- (\S+)/, '$1 = $2' );

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.