将字符串插入/插入html字符串

时间:2020-04-08 02:39:37

标签: javascript html

我正在从服务器中获取一些html,它以字符串形式返回,但是我需要在html字符串中的所有target='_blank'标记中插入<a>。除了遍历整个字符串以寻找<a然后插入target='_blank'之外,还有更好或更有效的方法吗?

5 个答案:

答案 0 :(得分:2)

存在使用正则表达式的.replace方法。

var string = "<a href='https://stackoverflow.com/'>Stack Overflow</a><br><a href='https://google.com/'>Google</a><br><a href='https://wikipedia.com'>Wikipedia</a>";

var newString = string.replace(/<a/g, "<a target='_blank'");

document.body.innerHTML = newString;
body {
  background-color: white;
}
<body>
</body>

答案 1 :(得分:1)

首先将HTML放入您的页面。然后立即运行修改DOM元素以包含所需属性的代码。

例如,如果要将html放入ID为container的容器元素中:

document.querySelectorAll('#container a').forEach(element => {
  element.setAttribute('target', '_blank')
})
<div id="container">
     <a href="http://google.com">Google</a>
     <a href="http://wikipedia.com">Wikipedia</a>
</div>

答案 2 :(得分:1)

您可以使用返回为字符串的html代码创建html元素,然后OTHER_LDFLAGS = "-lSomething ";并最终将getElementsByTagName('a')属性设置为target,例如:

"_blank"

请记住使用template literals`来转义html字符串的双引号和单引号。

答案 3 :(得分:1)

 clang++: error: no such file or directory: 'jni/../lib/libavformat.a'

答案 4 :(得分:0)

不要使htmlString复杂得多。渲染HTML之后,使用此衬纸:

[...document.links].forEach(a => a.target = '_blank');

演示

[...document.links].forEach(a => a.target = '_blank');

// Just to check if each link is correctly modified
console.log([...document.links].map(a => a.outerHTML));
a {
  font: 700 3vw/1.45 Verdana;
  display: block;
  width: max-content;
  margin-bottom: 8px;
  text-decoration: none
}

a:hover {
  text-decoration: underline;
}

.as-console-wrapper {
  width: 80%;
  min-height: 100%;
  margin-left: 20%;
}
<a href='example.com'>LINK</a>
<a href='example.com'>LINK</a>
<a href='example.com'>LINK</a>
<a href='example.com'>LINK</a>

相关问题