简体   繁体   中英

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?

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 .

demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM