Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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">
like image 441
panthro Avatar asked Nov 14 '16 11:11

panthro


2 Answers

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="mypath/assets/img/image.jpg">

like image 173
vincent Avatar answered Nov 19 '22 15:11

vincent


First I would capture /assets as follows:

(\/assets)

And then I would apply the following substitution:

my-path$1

So if my original sentence was:

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

I would get something like:

<img src="my-path/assets/img/image.jpg">

This is the code regex101 generated for my regular expression:

const regex = /(\/assets)/g;
const str = `<img src="/assets/img/image.jpg">`;
const subst = `my-path\$1`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log('Substitution result: ', result);

UPDATE: If you only want to match those lines that also contain src then you could use the following matching pattern:

(src=")(\/assets)

And this how you would replace it:

$1my-path$2
like image 25
Xavier Alvarez Avatar answered Nov 19 '22 14:11

Xavier Alvarez