Javascript 使用字符串替换在数据集上迭代

Javascript 使用字符串替换在数据集上迭代,javascript,regex,loops,Javascript,Regex,Loops,我试图迭代一组li元素,并用字符串替换它们的dataset属性 问题是,我只想替换与另一个字符串匹配的部分,然后保留其数据集的其余部分不变 HTML如下所示: <ul class="myUL"> <li data-path="http://example.com/test1/">Link1</li> <li data-path="http://example.com/test1/test2">Link2</li>

我试图迭代一组
li
元素,并用字符串替换它们的dataset属性

问题是,我只想替换与另一个字符串匹配的部分,然后保留其数据集的其余部分不变

HTML如下所示:

<ul class="myUL">
   <li data-path="http://example.com/test1/">Link1</li>
    <li data-path="http://example.com/test1/test2">Link2</li>
    <li data-path="http://example.com/test1/test2/test3">Link1</li>
</ul>
    链接1 链接2 链接1
以下是我正在尝试的:

var UL = document.querySelector('.myUL');
var children = UL.getElementsByTagName("li");
var URL = "http://example.com/test1/";
var newURL = "http://example.com/replaced/";

for (i = 0; i < children.length; ++i) {
   var li = children[i];
   var datapath = li.dataset.path;
   if(datapath.match(URL)) {
        li.dataset.path = datapath.replace(datapath, newURL);
    }

}
var UL=document.querySelector('.myUL');
var children=UL.getElementsByTagName(“li”);
变量URL=”http://example.com/test1/";
var newURL=”http://example.com/replaced/";
对于(i=0;i
但是,这只是用字符串替换整个URL。我只想替换与字符串匹配的部分。所以输出应该是这样的:

<ul class="myUL">
   <li data-path="http://example.com/replaced/">Link1</li>
    <li data-path="http://example.com/replaced/test2">Link2</li>
    <li data-path="http://example.com/replaced/test2/test3">Link1</li>
</ul>
    链接1 链接2 链接1
如果有人能提供帮助,我将不胜感激。我希望有一种方法可以从.match()语句中获取剩余的内容,然后我可以简单地将其附加到新的URL中


这是我正在处理的小提琴

您想用
newURL
替换
URL
,而不是用您当前拥有的
newURL
替换
datapath

因此:

变成:

li.dataset.path = datapath.replace(URL, newURL);


我还建议您在执行这一行之前不需要if语句

//if(datapath.match(URL)) {
    //should work fine just with this
    li.dataset.path = datapath.replace(URL, newURL);
//}

不错。非常感谢。我就快到了!我会接受当我can@user3143218很高兴我能帮忙:)
//if(datapath.match(URL)) {
    //should work fine just with this
    li.dataset.path = datapath.replace(URL, newURL);
//}