ai didi

javascript - 在字符串中出现的所有链接上添加 target=_blank

转载 作者:行者123 更新时间:2023-11-30 09:30:55 24 4
gpt4 key购买 nike

如何在函数内使用 javascript 为字符串中所有出现的 href 标记添加 target="_blank"?

例如:

输入字符串:

var input = 'this is a test string <a href="https://example.com" ui-link="https://example.com">example</a>, and this is another test string <a href="http://example2.com">example 2</a>.'

var output = convertString(input);

output should equal: 'this is a test string <a target="_blank" href="https://example.com" ui-link="https://example.com">example</a>, and this is another test string <a target="_blank" href="http://example2.com">example 2</a>.'

最佳答案

只需替换'

var input = 'this is a test string <a href="https://example.com" ui-link="https://example.com">example</a>, and this is another test string <a href="http://example2.com">example 2</a>';

function convertString(input){
return input.split('<a').join('<a target="_blank"')
}

document.body.appendChild(document.createTextNode(convertString(input)))

关于javascript - 在字符串中出现的所有链接上添加 target=_blank,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46354924/

24 4 0
文章推荐: javascript - jQuery - 更改未创建的 div 元素的样式
文章推荐: javascript - 如何在 ShellJS 命令执行期间运行 cli-spinner?
文章推荐: javascript - ReactJS - Handsontable - 确定更改
文章推荐: javascript - react 类 : setState does nothing (and no errors reported)
行者123
个人简介

我是一名优秀的程序员,十分优秀!

滴滴打车优惠券免费领取
滴滴打车优惠券
全站热门文章
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com