最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

regex - replace javascript regexp matched group with a dollar sign - Stack Overflow

programmeradmin2浏览0评论

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 :)

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 :)

Share Improve this question edited May 12, 2017 at 19:55 cweiske 31.2k15 gold badges147 silver badges205 bronze badges asked Mar 26, 2014 at 1:04 xShirasexShirase 12.4k4 gold badges54 silver badges86 bronze badges 1
  • $1 means "the first matched characters". To escape $, try $$. – Derek 朕會功夫 Commented Mar 26, 2014 at 1:14
Add a ment  | 

1 Answer 1

Reset to default 13
"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 (i.e. if you say "\$", it bees "$" before being passed as an argument, so replace never sees the escaping).

发布评论

评论列表(0)

  1. 暂无评论