0

I have this html image with a source:

<img src="http://url/test/img-429x600.jpg" class="test-class">

What I need is, to remove the "-429x600" part from the source. I can achieve that using the following jquery:

var imgSrc = $('.test-class').attr("src");
imgSrc = imgSrc.replace("-429x600", "");    
$('.test-class').attr("src", imgSrc);

Now my problem is, how can I remove the same string but if I don't know the numbers that will appear there. I want to be able to remove that part of the string but without specifying the exact value.

https://jsfiddle.net/9hmyyrh3/

6
  • If it's always a .jpg, you could just chop off everything after the first X characters and append .jpg back onto it. Commented Aug 7, 2015 at 15:47
  • what is your src attr? Commented Aug 7, 2015 at 15:47
  • Ye, well the problem is that it can have other formats also, and the name of the image can have "-" characters in it as it can also have numbers so I can't basically remove numbers. :/ Commented Aug 7, 2015 at 15:48
  • What do you mean? The original src attr? Commented Aug 7, 2015 at 15:50
  • yeah, value in src attribute Commented Aug 7, 2015 at 15:50

2 Answers 2

1

first take name and then extension, remove unwanted string

var abc = $('.test-class').attr("src");
var ext = abc.substr(abc.lastIndexOf('.')+1);
var name = abc.slice(0,-12);
var image_name = name+"."+ext;
$('.test-class').attr("src", image_name);

Demo: https://jsfiddle.net/farhanbaloch/9hmyyrh3/1/

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

Comments

1

I broke this down into a step by step just to make it readable

var imgSrc = $('.test-class').attr("src");
var img = /[^/]*$/.exec(imgSrc)[0];
var newImg = img.replace(/-.*\./g, ".");    

It strips the image name, looks for the "-STUFF." and replaces it with just "."

https://jsfiddle.net/2yngbx96/

UPDATE: OK, a new version that takes into account a hyphen mid-name and uses the last hyphen as it's filter point

var imgSrc = $('.test-class').attr("src"); // get image src
var url = imgSrc.substring(0, imgSrc.lastIndexOf("/") + 1); // grab the base url
var img = /[^/]*$/.exec(imgSrc)[0]; // get the image name
var imgParts = img.split('.'); // seperate image to get extension
var imgName = /.*-/.exec(img)[0]; // get image name prior to last "-"
var newURL = url + imgName.substring(0,imgName.length - 1) + "." + imgParts[1]; // create new image url
$('.test-class').attr("src", newURL);

https://jsfiddle.net/kf4xeeq1/

2 Comments

The only problem I've checked in your code is that if I have a "-" in the middle of the name of the image it will break the link
Yep, that's it. Thanks ;)

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.