-1

I'm implementing the srcset attribute on some images within a site and hit an issue because Chrome doesn't like srcset image urls that contain spaces. My source HTML has a number of image tags which look like:

<img src="/images/image 1.jpg" alt="My alt" sizes="100vw" srcset="/images/image 1 136.jpg 136w, /images/image 1 165 165w, /images/image 1 286 286w">

What I'm wanting to do is to replace the spaces in the srcset with %20 so it looks like:

<img src="/images/image 1.jpg" alt="My alt" sizes="100vw" srcset="/images/image%201%20136.jpg 136w, /images/image%201%20165 165w, /images/image%201%20286 286w">

To simplify the problem - if I can replace the n spaces in the src on the following then I can fix my problem:<img src="/images/image any number of spaces.jpg" />

I think the only solution would be using lookbehind but as I'm doing this in javascript its not supported so I'm stumped. I would normally use something like:myText.replace(/src=".[^"]*"/gi,'%20') but this would replace the whole string. See this example.

I suspect this problem can't be solved (and it is only for a temporary measure while we test out the impact of srcset after which I can fix it at source) - but I don't know if there is something I'm not thinking of that would enable me to achieve what I want.

Code Ninja
  • 727
  • 1
  • 7
  • 9
  • getElementsByTagName to get the images, get/setAttribute with srcset each one using the latter with encodeURIComponent. – Alex K. Jun 12 '17 at 12:28
  • How did you create the HTML? Could you post your code? – Alessandro Jun 12 '17 at 12:31
  • The HTML is coming from a 3rd party, so I'm not able make any changes directly to it. Its a returned HTML string with many images that I'm trying to manipulate into srcset tags (I'm able to make all the other changes I need to the feed except for this). – Code Ninja Jun 12 '17 at 12:50

2 Answers2

0

Try this:

// your link    
//    var link = "/images/image 1 136.jpg 136w, /images/image 1 165 165w, /images/image 1 286 286w"
//   var src = link.substring(0, link.indexOf('.jpg'))
// your result
//    var result = encodeURI(src) + link.substring(link.indexOf(.jpg) + 4)

Sorry, I misunderstood question

guest
  • 706
  • 7
  • 15
  • Yeah - I considered if it was just a single tag I could extract it, fix it and drop it back in, but unfortunately not – Code Ninja Jun 12 '17 at 12:53
0

You could split it into two groups and replace the spaces in the second group

(img src="\/images\/)(.*\d\s\d{3}?)(\.jpg)?(\s\d{3}w)

img src="/images/     image 1 136.jpg 136w
img src="/images/     image%201%20136.jpg 136w

see it here

Mr Mystery Guest
  • 1,464
  • 1
  • 18
  • 47