简体   繁体   中英

replace javascript regexp matched group with a dollar sign

This one should be pretty simple :

Let's take the string : str="1.99 or 4.89"

I want to add a dollar sign in front of the amounts.

I tried :

str.replace(/(\d\.\d\d)/g,"$$1"));

it gives me : "$1 or $1"...

So I'm stuck with doing :

str.replace(/(\d\.\d\d)/g,"$ $1").replace(/\$ /g,'$')

It works but I'm sure there's a better way! I've tried escaping both $ signs, and a few other things... Looking forward to your answers :)

"1.99 or 4.89".replace(/(\d\.\d\d)/g, "$$$1")
// => "$1.99 or $4.89"

Since $ is special in replacement string, it must be escaped into $$ for a literal $ . It is not escaped using the \\ character, which is a general string escape mechanism, and processed before the string reaches replace (ie if you say "\\$" , it becomes "$" before being passed as an argument, so replace never sees the escaping).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM