-1

I need to get the img src on button click and only change the value between the first and second forward slashes from "galleryhomelarge" to "testtext".

Js fiddle link: quick setup of my scenario

Jquery Code: `$(function () { var image = ""; var imageSrc = ""; var imageCaption = ""; var newImageCon = ""; var newImageSrc = "";

$('#button').click(function () {
    image = $('#demoimg');
    imageSrc = image.attr('src');
    imageCaption = image.attr('alt');
    newImageCon = $('#newimg-con');
    newImageCon.html("Old Image Source: " + imageSrc + "<br />Image Caption: " + imageCaption + "<br />New Image Source: " + newImageSrc);
});

}); ` Thanks,

Ian

3 Answers 3

2

You can simply do:

var src = $("img").attr("src");
src.replace("/galleryhomelarge/", "/testtext/");
$("img").attr("src", src);

I imagine that your links to images are consistent and there is not high probability that you have galleryhomelarge in a place other than between first and second slashes.

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

2 Comments

Wow that was simple! even way more semantic highly understandable. I presume that Greg used the forward-back slashes to escape any symbols or spaces present. Yes, you're right the the link will always be consistent and I can safely use your code
What about if the directory name changes? You will have to come back and change this source to suit. I think regular expressions are the way to go in this situation.
1

I think u want this:

$('img').each(
function(){
    var src = $(this).attr('src');
    if (src.indexOf('/') === 0){
        this.src = src.replace('/','');
    }
});

1 Comment

This stops at the first forward slash and replaces that only. it helps but was looking to replace the string all the way from this point till the next forward slash.
1

newImageSrc = imageSrc.replace(/(.*?)\/(.*?)\/(.*?)/, '$1/testtext/$3');

2 Comments

Did the job mate! thanks! I find it quite difficult to understand the forward-backward slash pattern and the dot-asterisk-questionmarks's meaning within the javascript line.. and the $1 and $3
It's called back referencing, check it out at stackoverflow.com/questions/3235763/… The first and last forward slashes are the start end end of the reg ex, the ones in the middle need to be escaped with backslashes to make it work. The brackets tells regex to capture those strings. The back references ($1 etc) refer to the captured group by index.

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.