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">
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">
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With