简体   繁体   中英

javascript/jquery remove relative path from url

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?

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

Use split function:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM