查找纯文本链接并将其转换为超链接
find links in plain text and convert them to hyperlinks
我的要求是,如果我收到消息,如果它在消息中有任何超链接(如 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>
我的要求是,如果我收到消息,如果它在消息中有任何超链接(如 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>