panthro panthro - 26 days ago 8
Javascript Question

Prepend a string with regex?

I am using the following to prepend my

asset/img
paths with a new string, in this case
my-path
.

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

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