好吧,我现在感觉很愚蠢,但是我真的想不出解决办法,即使有人可以将我指向正确的方向,这也很棒。
我需要一个JavaScript脚本,该脚本将检查页面的DOM,并在找到美元值时将其乘以1.5。
数字的格式可能为$ 1,111.11或$ 1111.11,或者可能没有美元符号。
我将首先解决什么可能的事情?!
如果只需要获取值,而不是拥有值的元素...
const { innerHTML } = document.documentElement
const regex = /(\d[\d.,]+|\d)/gm;
innerHTML.match(regex)
如果需要通过其内部值获取元素,则为:
const allPageElements = document.getElementsByTagName('*')
[...allPageElements]
.filter(element => /(\d[\d.,]+|\d)/.test(element.innerText))
.forEach(element => element.innerText = 'some new value')
可能您需要改进此正则表达式,因为它将匹配具有数值的所有元素
您可以遍历所有元素,将正则表达式的匹配项替换为该数字乘以1.5(在解析出逗号之后):
var elements = document.getElementsByTagName("*");
for(var i = 0; i < elements.length; i++){
var matches = elements[i].innerText.match(/(\d[\d.,]+|\d)/gm);
if(matches !== null){
for(var j = 0; j < matches.length; j++){
elements[i].innerHTML = elements[i].innerHTML.replace(matches[j], (Number(matches[j].replace(/,/g, "")) * 1.5).toFixed(2));
}
}
}
为正则表达式贷给Macabeus。我只是将其复制并应用于元素搜索和替换。
[如果您对原始算法的伪代码感兴趣,这使我意识到一个过程需要花费多长时间,实际上可以使其变得足够有效,可以在不破坏页面上任何元素或过程的情况下使用:
for every element in page
if it doesn't have an id
manually assign a uuid
save the uuid in a global uuid array
for every element in page
grab the text from the element and store it in a global object with the uuid as its key
replace all numbers in that object[uuidKey]'s text with num * 1.5
for every uuidKey in our uuid object
set the text of the element with that uuid to the associated stored value
for every uuid in our global uuid array
remove the id from the element with this uuid