panthro panthro - 1 year ago 84
Javascript Question

Prepend a string with regex?

I am using the following to prepend my

paths with a new string, in this case

str.replace(/=('|")(\/?assets\/img)/g, "my-path$&");

Unfortunately it's prepending before the
so I get something like:

<img srcmypath="/assets/img/image.jpg">

How can I get it to prepend after the
So I get:

<img src="mypath/assets/img/image.jpg">

Answer Source

You can use groups to reference the stuff you want after replacing. Groups are defined with parentheses.

str.replace(/(=['"])(\/?assets\/img)/g, '$1mypath$2')
              ^^^^^  ^^^^^^^^^^^^^^      ^^      ^^- text of 2nd group
              1st     2nd group          |       
              group                      text of first group

will result in

<img src="mypathassets/img/image.jpg">

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download