2

I'm using jquery to find and retrieve several img src's from the DOM, however the src's are in relative path format like this:

src="../../../../../dynamic/eshop/product_images/thumbnail_cache/366x366/042-1392_13760000.1.jpg"

I need to remove all the trailing slashes and append an absolute url. Is there anyway to achieve this without using regex in javascript or jquery?

6
  • you mean preceding slashes and dots? Commented Jun 14, 2013 at 10:28
  • Well a lot of people say regex is overkill for a lot of things, so I was wondering if there was another method. Regex is also welcome but I don't know the syntax very well Commented Jun 14, 2013 at 10:29
  • @Prisoner yea that's what I mean Commented Jun 14, 2013 at 10:30
  • You want to change the src to a different URL, or to the same URL, but with an absolute path? Because the current absolute path should be available in the this.src property of the of the node (which is different to the relative path held in the this.getAttribute('src') property. Commented Jun 14, 2013 at 11:32
  • @DavidThomas I want the absolute path of the same URL. So... I should use this.src instead of .attr('src')? Commented Jun 14, 2013 at 11:53

2 Answers 2

5

Given the URL

var url = '../../../../../dynamic/eshop/product_images/thumbnail_cache/366x366/042-1392_13760000.1.jpg';

Using regex

var fullurl = url.replace(/^.+\.\//,'');

Using index

var inx = url.lastIndexOf('./');
var fullurl2 = url.substring(inx+2, url.length)

Normal replace (if you're sure you only have ../)

url.replace(/\.\.\//g, '');

FIDDLE

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

2 Comments

thanks for the reply, does the regex method work with any length of preceding slashes and dots? I mean maybe some url's have shorter and some have longer slashes and dots
@user2028856 jsfiddle.net/a4rnY/2 yes it does. Now that I think about it a normal replace should also work
0

Use split function:

var segments = "/url/to/img".split('/');
alert(segments[segments.length-1]); // your value

2 Comments

thanks for the answer, but could you please provide a small explanation how this works?
@user2028856, answer corrected see documentation. Function split your string by separator and create array of segments, to example code in answer return ['url','to', 'img'], your image name located in last segment.

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.