Home > Software engineering >  Javascript replace img tab src value inside string
Javascript replace img tab src value inside string

Time:04-01

I have a string which contains some text and HTML tags and I want to add a query param to each img tag, for example, I have this string:

'<p>Lorem ipsum <img src="https://www.abc./com/myImg.png" />. Another lorem ipsum <img src="https://www.abc./com/myImg2.png" /></p>'

and I would like to replace it with this one:

'<p>Lorem ipsum <img src="https://www.abc./com/myImg.png?myParam=xyz" />. Another lorem ipsum <img src="https://www.abc./com/myImg2.png?myParam=xyz" /></p>'

so basically I want to append to each src attribute a query param. I want to use replace with a regExp, but I am not sure which regExp to use to modify all the src(s), no mater what is the extension of the image. I don't want to target the image extension, insted I am thinking of something like targeting the end of the src attribute value for each img tag. Please advise. Thanks!

CodePudding user response:

I don't think you should use RegEx for this. It is simpler to parse the HTML using DOMParser, then get all elements with <img> tags in that parsed document and manipulate the src attribute as required using URL.searchParams.append(). This way you will use trusted JS APIs that are tested and you don't have to worry about URL encoding parameters or whether there already is a query parameter on the src or not.

// create parser
const parser = new DOMParser();
// I have added a query parameter to the first string so you see it does also work
// when there already is a query parameter
const html = `<p>Lorem ipsum <img src="https://www.abc./com/myImg.png?a=b" />. Another lorem ipsum <img src="https://www.abc./com/myImg2.png" /></p>`;
// parse the HTML
const doc = parser.parseFromString(html, "text/html");

// get all images tags within the document
const images = doc.getElementsByTagName("img");

// loop over all img elements
for(let img of images){
  // get the src attribute
  const src = img.getAttribute("src");
  console.log("Before:", src);
  // build a new URL to be able to use the JS API to append search params
  // this way we don't need to be concerned wether it's the first or one of many parameters
  const params = new URL(src);
  // add another parameter
  params.searchParams.append("myParam", "myParamValue");
  // update the img element
  img.setAttribute("src", params.toString());
  // show that update works
  console.log("After:", img.getAttribute("src"));
}

I don't know what you need to do with the newly set src value but you can get the string if you only need that using params.toString() or you can actually set it on the <img> element again using setAttribute().

To read on the safety of DOMParser I suggest this thread, and then evaluate if this solution is suitable for you.

CodePudding user response:

This using JQuery will append ?param=xyz to every img found when the document is ready:

$(document).ready((){
    $('img').each( ()={
      let src = $(this).prop('src')   '?param=xyz';
      $(this).prop('src', src);
    });
});

Or instead following your expectations of parsing a string with such contents:

let subject = '<p>Lorem ipsum <img src="https://www.abc./com/myImg.png" />. Another lorem ipsum <img src="https://www.abc./com/myImg2.png" /></p>';

//I'm doing some assumptions here and it won't be 100% safe
let myregexp = /<\s*?img[^>] ?src="(?<imgsrc>[^"] )"/g;
let result = subject.replace(myregexp, function(match, imgsrc) {
  return imgsrc   "?param=xyz";
});
  • Related