Replace http links with anchor tag

Multi tool use
Replace http links with anchor tag
So i'm building a chat-client where i read the incoming-messages through json.
However, I would like to be able to convert URLs to clickable anchor-tags instead. I've looked around but haven't really found any posts asking or getting an answer about this.
This is my current code:
if (json.type === 'message') {
var val;
var str = json.data.text; //message-string
var here = str.match("([^s]+)"); // match any word until space <---| merge
if (!here.search(/^http[s]?:///)){ //if it contains http / https <---| these?
val = '<a href="' + here + ""> [Link] </a>";
}
addMessage(json.data.author, val, json.data.color, new Date(json.data.time));
}
else {
console.log('Hmm..., I've never seen JSON like this:', json);
}
Thanks
1 Answer
1
You're never using val
, but it would probably be a lot easier to use replace
immediately. You may want to add target="_blank"
to ensure that the links open in a new window rather than replacing the chat page. (the target="_blank"
seems not to work in embedded snippet due to sandboxing, but it works on an ordinary page)
val
replace
target="_blank"
target="_blank"
const text = 'here is a message with a link to https://www.google.com and another link to https://stackoverflow.com';
const changedText = text.replace(
/(https?://)([^ ]+)/g,
'<a target="_blank" href="$&">$2</a>'
);
console.log(changedText);
document.body.innerHTML += changedText;
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.