查找纯文本中的链接并将其转换为超链接



我的要求是,如果我收到消息,如果它在消息中有任何超链接(如www.gmail.com等)那么它必须显示为链接,如锚标记链接与下划线和蓝色(如标签)

我的JavaScript代码是. js

//var postMessage = MessageGet($("#PrivateConversation #ConversationTextarea"));
var urlRegex = /(((https?://)|(www.))[^s]+)/g;
var detectURL = postmsg.match(urlRegex);
//console.log(detectURL);
var resultPost = '<a href= "' + detectURL + '" role="link" > ' + postmsg + '</a>';
console.log(postmsg);

从上面我得到的文本只有当它有超链接,它也显示在文本格式

我嵌入了一个片段,它应该解决你的问题:你的代码是正确的,但它有一些问题在控制台日志和替换链接与正确的内容。

function transformHyperlinks() {
const postmsg = document.getElementById("start").value;
const urlRegex = /(((https?://)|(www.))[^s]+)/g;
const detectURL = postmsg.match(urlRegex);
let resultPost = postmsg
detectURL.forEach(url => {
resultPost = resultPost.replace(url, '<a href= "' + url + '" role="link" > ' + url.trim() + '</a>')
}) 
document.getElementById("end").innerHTML = resultPost;
}
<h2>Old text</h2>
<textarea id="start">test https://facebook.com https://www.google.com test</textarea>
<button onclick=transformHyperlinks()>Transform Hyperlinks</button>
<h2>New text</h2>
<div id="end"></div>

function transformHyperlinks() {
const postmsg = document.getElementById("start").value;
if (!postmsg) {
console.error("The element with ID 'start' was not found.");
return;
}
const urlRegex = /(https?://(www.)?[-a-zA-Z0-9@:%._+~#=]{1,256}.[a-zA-Z0-9()]{1,6}b([-a-zA-Z0-9()@:%_+.~#?&//=]*))/g;
const detectURL = postmsg.match(urlRegex);
let resultPost = postmsg;
if (detectURL) {
detectURL.forEach(url => {
resultPost = resultPost.replace(url, `<a href="${url}" role="link">${url}</a>`);
});
}
const endEl = document.getElementById("end");
if (!endEl) {
console.error("The element with ID 'end' was not found.");
return;
}
endEl.innerHTML = resultPost;
}

最新更新