在原型属性迭代中替换函数

Replace function in prototype attributes iteration

我正在尝试替换所有属性中的连字符

<a href="/page" id="someId" data-country="north-america" data-state="north-dakota">North Dakota</a>

像这样:

var el = document.getElementById('someId');
Array.prototype.slice.call(el.attributes).forEach(function(item) {
   item.value.replace('-','_');
   console.log(item.value);
});

不太明白为什么它实际上没有用下划线替换连字符。我错过了什么吗?

String.prototype.replace() returns 一个新的字符串,它不会改变原来的字符串。只需分配新值即可完成。

item.value = item.value.replace('-','_');

引自 MDN 文档:

This method does not change the String object it is called on. It simply returns a new string.