Newbie
Newbie

Reputation: 21

How to replace img tag with attribute and specific class only

I'm newbie in javascript and looking for some regex or way which can replace image tag with their attributes.

Image tag can be multiple without any unique id and I want to replace only those image tags which have particular class.

For example I've string like :

var str = 'hi <img dataattr1="att1" src="abc" class="img specificclass" dataattr2="att2" dataattr3="att3" /> <img dataattr1="newatt1" src="abc" class="img specificclass"  dataattr2="newatt2" dataattr3="newatt3" /> some more tag <img dataattr1="moreatt1" src="abc" class="img specificclass"  dataattr2="moreatt2" dataattr3="moreatt3" /> <img dataattr2="noreplace" src="abc" class="img" /> end';

so its output should be like this :

hi :::att2::: :::newatt2::: some more tag :::moreatt2::: <img data-attr1="noreplace" src="abc" class="img" /> end

What I tried till now is :

var str = 'hi <img dataattr1="att1" src="abc" class="img specificclass" dataattr2="att2" dataattr3="att3" /> <img dataattr1="newatt1" src="abc" class="img specificclass"  dataattr2="newatt2" dataattr3="newatt3" /> some more tag <img dataattr1="moreatt1" src="abc" class="img specificclass"  dataattr2="moreatt2" dataattr3="moreatt3" /> <img dataattr2="noreplace" src="abc" class="img" /> end';

var rgx = /<img[^>]*class="specificclass"[^>]*>/;

var regex = /<img.*?dataattr2='(.*?)'/;
var src = regex.exec(str)[1]
str = str.replace(rgx,src);

console.log(str);

but its giving an error and I'm not if its even right way to do it or not

Upvotes: 1

Views: 252

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074158

I wouldn't use regex for this, it's famously brittle and problematic for non-regular texts like HTML.

Instead, I'd use the DOM parser built into the browser (you've tagged jQuery, so I'm assuming you're doing this on a browser or in another environment with a DOM):

var str = 'hi <img dataattr1="att1" src="abc" class="img specificclass" dataattr2="att2" dataattr3="att3" /> <img dataattr1="newatt1" src="abc" class="img specificclass"  dataattr2="newatt2" dataattr3="newatt3" /> some more tag <img dataattr1="moreatt1" src="abc" class="img specificclass"  dataattr2="moreatt2" dataattr3="moreatt3" /> <img dataattr2="noreplace" src="abc" class="img" /> end';

// Parse it and wrap it in a div
var frag = $("<div>").append($.parseHTML(str));
// Find the relevant images
frag.find("img.specificclass[dataattr2]").each(function() {
  // Replace the image with a text node containing :::[dataattr2]:::
  var $this = $(this);
  $this.replaceWith(document.createTextNode(":::" + $this.attr("dataattr2") + ":::"));
});
// Get the HTML of the result
var str = frag.html();

console.log(str);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

Upvotes: 1

Related Questions