Reputation: 6173
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
Upvotes: 4
Views: 1703
Reputation: 370679
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)
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;
Upvotes: 3