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">
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">
Share
Improve this question
edited Nov 14, 2016 at 11:34
invernomuto
10.2k5 gold badges42 silver badges53 bronze badges
asked Nov 14, 2016 at 11:33
panthropanthro
24.1k70 gold badges205 silver badges350 bronze badges
1
- why don't you simple use str.replace("assets/img", "my-path$&"); . – Ajay Pal Commented Nov 14, 2016 at 11:47
3 Answers
Reset to default 3You 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
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"));
}