这很简单,我以前已经做过了,但现在不能让它发挥作用。
我需要在href下面更改图像的名称
var href="https://www.facebook.com/sharer/sharer.php?u=http://myurl.com/&description='tets'&picture=http://myurl.com/img/name-1654-45654.jpg"
$('.share, .share-2').prop('href', function () {
$(this).replace(/(picture=).*?(&)/,'$1' + imgNew + '$2');
}); 发布于 2017-06-08 12:49:25
replace函数是string的一个方法,因此不能从$(this)调用replace,因为它是jQuery对象,而不是字符串。
如果需要更改href属性,只需使用this.href = ...。
编辑:在使用jQuery.prop方法时,应该按照docs的建议使用它。
$(".some-element").prop('some-prop', function(index, old_value){
// do something
return new_value;
});片段更新的
var new_img = "http://my.domain.com/img/my_new_image.jpg";
var regex_img = /\bpicture=[^&]*/
$('.share, .share-2').prop('href', function (index, old_href) {
var new_href = old_href.replace(regex_img, 'picture=' + new_img);
console.log(new_href);
return new_href;
}); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="https://www.facebook.com/sharer/sharer.php?u=http://myurl.com/&description='tets'&picture=http://myurl.com/img/name-1654-45654.jpg" class="share">Test</a>
<br>
<a href="https://www.facebook.com/sharer/sharer.php?u=http://myurl.com/&picture=http://myurl.com/img/name-1654-45654.jpg&description='tets'" class="share-2">Test-2</a>
发布于 2017-06-08 12:38:06
因为href字符串是一个URL,所以您可以利用URL对象。
var imgNew = 'http://example.com/img.png';
var href = "https://www.facebook.com/sharer/sharer.php?u=http://myurl.com/&description='tets'&picture=http://myurl.com/img/name-1654-45654.jpg";
var url = new URL(href);
url.searchParams.set('picture', imgNew);
console.log(url.href);
注意,目前并不是所有的浏览器都是支持,所以您可以使用聚脂填充。
发布于 2017-06-08 12:31:39
var href="https://www.facebook.com/sharer/sharer.php?
u=http://myurl.com/&description='tets'&picture=http://myurl.com/img/name-
1654-45654.jpg"
href.split('/')
["https:", "", "www.facebook.com", "sharer", "sharer.php?u=http:", "",
"myurl.com", "&description='tets'&picture=http:", "", "myurl.com", "img",
"name-1654-45654.jpg"]
href.split('/').length
12
href.split('/')[11]
"name-1654-45654.jpg"https://stackoverflow.com/questions/44435762
复制相似问题