我有一个带有源的html映像:
<img src="http://url/test/img-429x600.jpg" class="test-class">我需要的是,从源中删除"-429x600“部分。我可以使用以下jquery实现这一点:
var imgSrc = $('.test-class').attr("src");
imgSrc = imgSrc.replace("-429x600", "");
$('.test-class').attr("src", imgSrc);现在我的问题是,我如何删除相同的字符串,但如果我不知道数字,将出现在那里。我希望能够删除字符串的这一部分,但不需要指定确切的值。
发布于 2015-08-07 16:03:03
先取名称,然后再扩展名,删除不需要的字符串。
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);发布于 2015-08-07 16:09:12
我把它一步一步地分解,只是为了使它可读性。
var imgSrc = $('.test-class').attr("src");
var img = /[^/]*$/.exec(imgSrc)[0];
var newImg = img.replace(/-.*\./g, "."); 它剥去图像名,查找“-STUFF”。而代之以“公正”。
https://jsfiddle.net/2yngbx96/
更新: OK,这是一个新版本,它考虑了连字符的中间名,并使用最后一个连字符作为过滤点
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://stackoverflow.com/questions/31881658
复制相似问题