gpt4 book ai didi

Javascript .indexOf 匹配 HTML 符号

转载 作者:行者123 更新时间:2023-12-02 22:47:40 24 4
gpt4 key购买 nike

我以非常草率的方式解决了一个问题,寻找更好的解决方案。

任务

检查跨度是否包含 HTML 符号(箭头),如果存在,则用相反的符号替换该符号。

第一次尝试(不显示执行相反操作的第二个代码片段)

 first=headers[0].querySelector('span')
if (first.innerHTML.indexOf('↘') !== -1)
first.innerHTML=first.innerHTML.substring(0, first.innerHTML.length - 13)
first.innerHTML+=' ↖'

为什么这不起作用?

因为虽然   ===  但由于某种原因 === ↘

说真的!试试这个(在 IE 11 和 Chrome 中测试)

<span>test</span>
<script>
first=document.querySelector('span')
first.innerHTML+='&nbsp&searr;'
console.log(first.innerHTML)
</script>

在控制台中您会得到:test ↘

我丑陋的解决方案

我将箭头复制到我的 JS 代码中

if (first.innerHTML.indexOf('↘') !== -1)
first.innerHTML=first.innerHTML.substring(0, first.innerHTML.length - 7)
first.innerHTML+='&nbsp;&nwarr;'

那么...解决这个问题的正确方法是什么?

最佳答案

如果您担心代码中存在该文字箭头,那么您不应该担心。如果您的工具链配置正确,那么在代码中包含该文字箭头就可以了。

但是如果你想避免它,你可以使用 unicode 转义来代替:

const nwarr = "\u2196";
if (first.innerHTML.indexOf(nwarr) !== -1) {
first.innerHTML = first.innerHTML.substring(0, first.innerHTML.length - 7);
}
first.innerHTML += '&nbsp;&nwarr;'; // <== Did you mean &searr; here? The opposite of nwarr?

实时示例(在替换中使用:

const first = document.getElementById("first");

setTimeout(() => {
const nwarr = "\u2196";
if (first.innerHTML.indexOf(nwarr) !== -1) {
first.innerHTML = first.innerHTML.substring(0, first.innerHTML.length - 7);
}
first.innerHTML += '&nbsp;&searr;';
}, 800);
<span id="first">Foo&nbsp;&nwarr;</span>

<小时/>

两个旁注:

1.要替换内容,我会使用 replace 而不是 substring+=,尤其是这样你就没有魔数(Magic Number)(13, 7) 在您的代码中:

first.innerHTML = first.innerHTML.replace(/\&nbsp;\u2196/g, "&nbsp;&searr;");

您甚至可能允许某些浏览器使用字符实体而不是字符:

first.innerHTML = first.innerHTML.replace(/\&nbsp;(?:\&nwarr;|\u2196)/g, "&nbsp;&searr;");

实时示例(在替换中使用:

const first = document.getElementById("first");

setTimeout(() => {
first.innerHTML = first.innerHTML.replace(/\&nbsp;(?:\&nwarr;|\u2196)/g, "&nbsp;&searr;");
}, 800);
<span id="first">Foo&nbsp;&nwarr;</span>

2.我会避免对 innerHTML 进行文本操作。如果您分配给它,即使分配回它已经拥有的内容,它也会拆除您正在执行操作的元素内的所有元素(和其他节点),并创建新的替换元素和节点。

例如,您可以旋转文本节点:

const first = document.getElementById("first");

setTimeout(() => {
handleReplacement(first);
}, 800);

function handleReplacement(el) {
for (let child = el.firstChild; child; child = child.nextSibling) {
if (child.nodeType === 1) { // Element
handleReplacement(child);
} else if (child.nodeType === 3) { // Text
child.nodeValue = child.nodeValue.replace(/\u00A0\u2196/g, "\u00A0\u2198");
}
}
}
<span id="first">Foo&nbsp;&nwarr;</span>

关于Javascript .indexOf 匹配 HTML 符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58322435/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com