在2个单词之间替换一部分HREF



这很简单,我以前做过,但现在无法使它起作用。

我需要在下面的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');
}); 

由于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);

请注意,目前并非所有浏览器都支持所有浏览器,因此您可以使用polyfill。

replace函数是string的一种方法,因此您无法从$(this)调用replace,因为它是jQuery对象,而不是字符串。

如果您需要更改href属性,只需使用this.href = ...

编辑:当您使用jquery.prop方法时,您应该按照文档提出的方式使用它。

$(".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>

 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"

您应该将代码更改为以下一个。

  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(//(?=[^/]*$)/, '/newpicturename'));
       }); 

最后一个斜线和以下单词将被新图片名称替换。

一个例子

var str = "http://one/two/three/four";
console.log(str.replace(//(?=[^/]*$)/, '/newpicturename'));

最新更新