Kim Ber
Kim Ber

Reputation: 89

Can NOT add target attribute to an anchor

I'm trying to convert text URL to a clickable html link, everything goes fine but i can not add an attribute(target). I don't get any errors.
Here's the code:

 let text= 'https://www.google.com';
 let exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
 let text1=text.replace(exp, "<a href='$1'>$1</a>");
 let exp2 =/(^|[^\/])(www\.[\S]+(\b|$))/gim;
 let message = text1.replace(exp2, '$1<a target="_blank" href="http://$2">$2</a>');

Output: <a href="https://www.google.com">https://www.google.com</a>

Upvotes: 0

Views: 187

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075039

There's no need for two passes. Just include the target in your initial replacement:

let text= 'https://www.google.com';
let exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
let text1=text.replace(exp, '<a target="_blank" href="$1">$1</a>');
// -------------------------^---^^^^^^^^^^^^^^^------^--^-------^
console.log(text1);

Since you seemed to want double quotes around _blank (it's not necessary), I changed the quotes around your replacement string to ' (and used " around href).

Upvotes: 2

Related Questions