Reputation: 14470
I have some text with images without path and extension stripped down e.g to store in db:
<img src="BUS-icon">
OR (if it has path and extension already)
<img src=".../images/thumbs/BUS-icon.png">
I need to get the filename to replace with prefix and extension (if not added already) e.g:
'some text <img src=".../images/thumbs/BUS-icon.png"> another text '.replace(/src=['|"](.*?)['|"]/ig
function($1){
var filename=$1.match(/DESIRED REGEXP/)
return 'src="../images/thumbs/'+filename[0]+'.png"';
}
);
I need the DESIRED REGEXP
to convert following test
image 1 <img src="BUS-icon1">
image 2 <img src='BUS-icon2.png'>
image 3 <img src="../images/thumbs/BUS-icon3.png">
image 4 <img src='abc/BUS-icon4.png'>
To
image 1 <img src="../images/thumbs/BUS-icon1.png">
image 2 <img src='../images/thumbs/BUS-icon2.png'>
image 3 <img src="../images/thumbs/BUS-icon3.png">
image 4 <img src='../images/thumbs/BUS-icon4.png'>
Actual application knows the filename without path and extension and replacing src with complete path.
This seems to be working so far :
text.replace(/src=['"](.*?)['"]/ig,function($1,$2){
var filename=$2.match(/(?:.+\/)?([^."']+)/)[1]
return 'src="../images/thumbs/'+filename+'.png"';
})
Upvotes: 2
Views: 548
Reputation: 67968
^(image\s+\d+\s*<img\s*src=["'])((?:(?!\.\.\/images|"|').)*?["']>)$
Try this.Replace by $1../images/$2
.See demo.
http://regex101.com/r/dZ1vT6/18
Upvotes: 2
Reputation: 589
This should work:
var filename=$1.match(/(src=['"])?(.+\/)?([^."']+)/)[3]
Upvotes: 1