javascript - 替换子字符串 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";
解决方案
您可以将此 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
推荐阅读
- android - 使用反射时,Android 运行时 (ART) 中的“加载类”是什么意思?
- php - 我的 Ajax 代码有一个奇怪的问题。我该如何解决这个问题?
- javascript - Node.js,Child_process 运行 python 脚本 pandas 导入错误
- c# - Publish 正在生成 .nuget 包而不是类库 + 依赖项
- javascript - Express,Mssql 插入带变量的表
- angular - TS2551:“PostListComponent”类型上不存在属性“post”
- microservices - KrakenD 包罗万象的路径
- sql - 选择 sql 查询的第一行和最后 10 行
- cloudflare - Cloudflare:流量 -> 健康检查 - 403 响应代码不匹配错误
- r - 使用ggplotly时geom_tile瓷砖移位