首页 > 解决方案 > 替换子字符串 javascript

问题描述

我只需要替换字符串中的子字符串匹配我的正则表达式。

const text = "There are many variations of passages of Lorem Ipsum available,

<a href='https://stackoverflow.com/'>stackoverflow</a>

but the majority have suffered alteration in some form, by injected humor, or randomized words which 

<a href="/page2">page 2</a>

don't look even slightly believable.
If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text.
All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the";

我需要为所有外部超链接添加一个目标空白,就像

const text = "There are many variations of passages of Lorem Ipsum available,

<a target='_blank' href='https://stackoverflow.com/'>stackoverflow</a>

but the majority have suffered alteration in some form, by injected humor, or randomized words which 

<a href="/page2">page 2</a>

don't look even slightly believable.
If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of the text.
All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the";

标签: javascriptregexecmascript-6replacesubstring

解决方案


您可以将此 HTML 添加到元素,然后在所有链接上设置属性,而不是使用正则表达式:

const text = '...';
const div = document.createElement('div');
div.innerHTML = text;
[...div.querySelectorAll('a[href]')].forEach(a => a.setAttribute('target', '_blank'));
const result = div.innerHTML;

你的const中有_blank-ed HTML 。result


推荐阅读