如何在 JavaScript 中忽略 HTML 标记来替换两个索引之间的子字符串
我想替换两个索引之间文本中的子字符串。但我想在计算索引时忽略任何 HTML 标签。
例如
,如果文本是the best kitchen Knife,我想用“nice”替换从索引4到8的子字符串,因此输出应该是the Nice kitchen Knife
但是如果文本位于 HTML 标记中,例如
最好的菜刀
或者
最佳菜刀
开始计数。所以预期的输出应该是
the nice菜刀
我使用了以下代码,但它没有按我的预期工作。
function replaceBetween(origin, startIndex, endIndex, insertion) {
return (
origin.substring(0, startIndex) + insertion + origin.substring(endIndex)
);
}
用法:
replaceBetween("<li>the <span>best</span> kitchen knife</li>", 4, 8, "nice");
输出:
<li>nice<span>best</span> kitchen knife</li>
预期输出:
<li>The <span>nice</span> kitchen knife</li>
I want to replace a substring in a text between two indexes. But I want to ignore any HTML tag when counting the index.
For example
If the text is the best kitchen knife I want to replace the substring from index 4 to 8 with 'nice' so the output should be the nice kitchen knife
But if the text is in HTML tag like<li>the best kitchen knife</li>
or<li>the <span>best</span> kitchen knife</li>
and given indexes are 4 and 8, it should count from 'the' not from <li>
. So the expected output should be <li>the <span>nice</span> kitchen knife</li>
I used the following code but it doesn't work as I'm expecting.
function replaceBetween(origin, startIndex, endIndex, insertion) {
return (
origin.substring(0, startIndex) + insertion + origin.substring(endIndex)
);
}
Usage:
replaceBetween("<li>the <span>best</span> kitchen knife</li>", 4, 8, "nice");
Output:
<li>nice<span>best</span> kitchen knife</li>
Expected Output:
<li>The <span>nice</span> kitchen knife</li>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一种解决方案是检索
li 元素
的.innerText
。返回的值将不包含任何 html 标签,因此您可以根据需要操作文本。如果需要删除的标签,您必须将它们放回去(通过修改文本字符串以包含标签)并将li 元素
'.innerHTML` 设置为您的文本字符串(浏览器会将文本解释为 html 标记)。
.innerText
检索的结果显示在以下代码片段的日志中:One solution is to retrieve the
.innerText
of yourli element
. The returned value will not contain any html tags so you can manipulate the text as required. If the removed tags are needed, you'll have to put them back (by modifying the text string to include tags) and set theli element
'.innerHTML` to your text string (where the browser will interpret the text as html markup).
The result of the
.innerText
retrieval is shown in the log of the following snippet: