panthro
panthro

Reputation: 24061

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

Upvotes: 5

Views: 3671

Answers (3)

Vincent Sch&#246;ttke
Vincent Sch&#246;ttke

Reputation: 4716

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

Upvotes: 3

Xavier Alvarez
Xavier Alvarez

Reputation: 293

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

Upvotes: 2

nozzleman
nozzleman

Reputation: 9649

You could begin by trying sth. like

(img src=")(\/?)(assets\/img\/)(.*?)(")

and then use the capturing groups for your replacements as shown in this regex101 example

var testCases = [
	'<img src="assets/img/image.jpg">',
	'<img src="/assets/img/image.jpg">'
]

for(var i=0; i<testCases.length; i++)
{
	console.log(testCases[i].replace(/(img src=")(\/?)(assets\/img\/)(.*?)(")/g, "$1mypath/$3$4$5"));
}

Upvotes: 0

Related Questions