简体   繁体   English

有没有办法替换字符串的所有实例,但只有当它包含在用 javascript 向用户显示的 html 标记中时?

[英]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.

相关问题 正则表达式-如果HTML标记中不包含文本,则替换HTML字符串中的文本 - Regex - Replace text in HTML string when not contained within HTML tags Javascript:replace()除了html标签之外的所有内容 - Javascript: replace() all but only outside html tags 替换<a>HTML字符串中的</a>所有<a>标签</a> - Replace all <a> tags in HTML string Javascript用空白字符串替换html标签 - Javascript replace html tags with blank string 使用 JavaScript 在 HTML 字符串上使用 strip_tags 时,从允许的 HTML 标记中去除所有属性 - Strip all attributes from allowed HTML tags when using strip_tags on HTML string using JavaScript 仅当用户禁用javascript时显示背景 - Background is only shown when javascript is disabled by user 给定html字符串,最好的方法是仅剥离javascript中的锚HTML标记? - What's the best way to strip out only the anchor HTML tags in javascript, given a string of html? AngularJS - 呈现字符串中包含的HTML标记 - AngularJS - Render HTML tags that are contained in a string php 字符串仅在 html 标签内替换,即<here>一串的</here> - php string replace only within html tags ie <here> of a string javascript - 用html标签替换所有空格以包含剩余的单词 - javascript - replace all white spaces with html tags to enclose remaining words
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM