panthro panthro - 5 months ago 30
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">


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">