[英]Is there a way to replace all intstances of a string but only when it is contained in html tags shown to the user with javascript?
For example, if i wanted to replace "mystring" with "myotherstring" in例如,如果我想将“mystring”替换为“myotherstring”
<!DOCTYPE html> <html> <body> <h1 id="mystring">mystring</h1> <p>mystring</p> <script>mystring javascript blah</script> </body> </html>
how could i only replace it in the <h1>
and <p>
tags with javascript, or can i do it without js?我怎么能只用 javascript 替换
<h1>
和<p>
标签中的它,或者我可以在没有 js 的情况下做到这一点?
You can select the specific tags you're interested in and do the replacement.您可以 select 您感兴趣的特定标签并进行替换。
document.querySelectorAll("h1, p").forEach((el) => {
el.textContent = el.textContent.replace(/\bmystring\b/g, "myotherstring");
});
https://codesandbox.io/s/unruffled-firefly-ssb8cj?file=/src/index.js https://codesandbox.io/s/unruffled-firefly-ssb8cj?file=/src/index.js
Read more about the \b
(Word Boundary)阅读有关
\b
(字边界)的更多信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.