0

I have some javascript I need help with.

I have an image with a src tag. I would like to take the value of the src an replace it with a static value. The src value though is variable but always in the same structure.

So if my image url is:

a/en-uk/images/items/item_123456789_1_185x185.jpg

with javascript, I want to modify this to

a/en-uk/images/items/item_not_found_185x185.jpg

baring in mind, the a/en-uk/images/items/ and 123456789_1 parts the url are dynamic. So just want to replace 123456789_1 with not_found.

Any idea how I could do this with jquery? regexp?

2 Answers 2

2

You can add an id attribute to your image, for example myImage and then change it with JavaScript HTML:

<img src='YOUR_OLD_SOURCE' id='myImage' ... />

JS:

document.getElementById("myImage").src = "YOUR_NEW_SOURCE";

Here is a working JSFiddle

Note, you can also do it with jQuery although I did not think it required or helpful, the syntax would be: $("#myImage").attr('src','YOUR_NEW_SOURCE')

If you'd like you don't have to give your image an ID, you can also select based on the url as explained in this question.

Sign up to request clarification or add additional context in comments.

2 Comments

My preference is to modify existing source using a regexp or similar and not working with ids.
@amateur While it is possible to use regular expressions to parse HTML in this particular case it is generally a really bad idea, more often than not regular expressions for parsing parts of HTML fail, more generally if you'd like you're welcome to come to the JS chat room where I will gladly explain why that happens. However, take a look at the question I linked to at the bottom of my answer, you can select the "a" tags based on the URL they link to without modifying the source. I just thought that wasn't as clean.
-1
$('#myImage').attr('src',$(this).attr('src').replace('not_found','123456789_1'));

and vice versa

1 Comment

Please read the question. "baring in mind, the a/en-uk/images/items/ and 123456789_1 parts the url are dynamic."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.