[英]Add target=_blank on all link occurrences in a string
How can I add a target="_blank" on all occurrences of the href tag in a string, using javascript inside a function? 如何使用函数内的javascript在字符串中所有出现的href标记上添加target =“ _ blank”?
For example: 例如:
input string: 输入字符串:
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>.'
just replace ' 只需替换“
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)))
Simple quick and dirty solution: 简单快捷又肮脏的解决方案:
function convert(str) {
const a_tag = /<a (.*)>/g;
return str.replace(a_tag, '<a target="_blank" $1>');
}
The regex uses a capture group to hold onto the various existing attributes of the tag and pipe them into the replacement string at the position of $1
. regex使用捕获组来保存标记的各种现有属性,并将它们通过管道传递到$1
位置的替换字符串中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.