Shawn31313
Shawn31313

Reputation: 6052

Replacing using "$" gives weird results

I am trying to replace some text like:

I need the %r for the bike.

Where %r gets replaced with another value.

Lets say I replace %r with $$$$.

var text = 'I need the %r for the bike.';

return text.replace("%r", "$$$$");

Instead of getting the expected results of:

I need the $$$$ for the bike.

I get:

I need the $$ for the bike.

Is there something I'm missing here?

Upvotes: 3

Views: 64

Answers (1)

jfriend00
jfriend00

Reputation: 707416

$ is a special character in a replacement as you need $$ to get one resulting $ sign in the result. You will need extra $ chars to get what you want. See the MDN reference for .replace() for details.

Various special sequences in the replacement string are:

$$ - Inserts a "$"
$& - Insert the matched substring
$` - Inserts the portion of the string that precedes the matched substring
$' - Inserts the portion of the string that follows the matched substring
$n - Where n or nn are decimal digits, inserts the nth parenthesized submatch string, provided the first argument was a RegExp object.

Upvotes: 4

Related Questions