简体   繁体   中英

find links in plain text and convert them to hyperlinks

My requirement is if I received the message if it is having any hyperlinks in message (like www.gmail.com etc) Then It has to show as Links like Anchor tag links with with underline and blue color(as on tag)

my JavaScript code is .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);

From the above I am getting the text only if it is having hyperlinks also it is showing in text format

I embed a snippet which should solve your problem: your code was correct, but it had some problems in the console log and in replacing the links with the right content.

 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM