Home > database >  Any link will be clickable in comment section
Any link will be clickable in comment section

Time:10-10

I am absolute beginner,is there any chance to solve this problem. I want to make the comment section for my website so that if any one put/paste any link in the comment section so that link will be clickable and will take anyone to that link. like we did in youTube comment section.

CodePudding user response:

You can take the value of your input and use .replace with a Regular Expression.

const testString = "Hello, I contain a link https://stackoverflow.com/questions/69509275/any-link-will-be-clickable-in-comment-section";

const hyperlink = (textContent) =>
  textContent.replace(
    /(https?:\/\/[^\s] )/g,
    (href) => `<a href="${href}">${href}</a>`
  );

hyperlink(testString);

output>> 'Hello, I contain a link <a href="https://stackoverflow.com/questions/69509275/any-link-will-be-clickable-in-comment-section">https://stackoverflow.com/questions/69509275/any-link-will-be-clickable-in-comment-section</a>'

CodePudding user response:

This is how I would have approached your issue. Regular expressions are very powerful, but can be quite hard to come up with, and because of this I used this site

const UnchangedUrlsExist = text => {
    text = text.replace(/\<\a.* href\=\".*\".*\>\w \<\/\a\>/gi, "");
    // Now there are no <a> tags, so test for urls.
    // These can be http://www.google.com, https://google.com, www.google.com, google.com
    let regExp1 = /(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.] \.[a-zA-Z]{2,30}(\/\S*)?/;
    let regExp2 = /www.[a-zA-Z0-9\-\_] \.[a-zA-Z]{2,30}(\/\S*)?/;
    let url_is_present = text.search(regExp1) > -1 || text.search(regExp2) > -1;
    return url_is_present;
}


const ParseMessageText = async MessageText => {
            if(!UnchangedUrlsExist(MessageText)) {
            return MessageText;
        }
        // First use regExp1 because sometimes regExp2 can match INSIDE of regExp1
        let regExp1 = /(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.] \.[a-zA-Z]{2,30}(\/\S*)?/g;
        let regExp2 = /(?<!(http|https|ftp|ftps)\:\/\/)www.[a-zA-Z0-9\-\_] .*\.[a-zA-Z]{2,30}(\/\S*)?/g;
        let regExps = [regExp1, regExp2];
        for(let n = 0; n < regExps.length; n  ) {
            let prefix = n == 1 ? "http://" : "";
            let regExp = regExps[n];
            let href_array = MessageText.match(regExp) || [];
            let anchor_elmnt_html;
            for(let i = 0; i<href_array.length; i  ) {
                if(!UnchangedUrlsExist(MessageText)) {
                    return MessageText;
                }
                let href = href_array[i];
                let webpage_title = await GetUrlTitle(href) || href;
                webpage_title = webpage_title.length > 61 ? webpage_title.substring(0, 59)   "..." : webpage_title;
                anchor_elmnt_html = `<a class="external" target="_blank" href="${prefix href}">${webpage_title}</a>`;
                MessageText = MessageText.replace(href, anchor_elmnt_html ?? href);
            };
        };
        return MessageText;
};


function GetUrlTitle(url) {
    return new Promise(resolve => {
        try {
            $.ajax({
                url: "http://textance.herokuapp.com/title/" url,
                complete: function(data) {
                    resolve(data.responseText);
                }
            }).fail(er => {
                console.log(er);
                resolve(false);
            });
        } catch(errr) {
            console.log(errr);
            resolve(false);
        }
    });
}

function Demo() {
  window.event.target.disabled = true;
  ParseMessageText(`This is a link - ${document.querySelector("input").value}. Notice that the link text is the title of the webpage found at the address you entered.`).then(Result => {
    document.write(Result);
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<input placeholder="Enter a valid link" value="www.google.com" />

<button onclick="Demo()">Try it</button>

Tip: try to copy and paste the URL of this current question, to see what the link text will be.

CodePudding user response:

What is a good regular expression to match a URL?

please refer this page

you can use contenteditable for a HTML element to style the user input

here is a small example

<body>
    <div id="editable" class="edit" contenteditable onkeyup="myfun()"></div>
    <script>
        let ele = document.getElementById('editable');
        function myfun() {
            let val = ele.innerText;
            let urlArray = val.match(/https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\ ~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\ .~#?&//=]*)/)
            let newVal = val;
            urlArray.forEach((url) => {
                newVal = newVal.replace(url, `<a href="${url}">${url}</a>`)
            })
            ele.innerHTML = newVal;//make sure this is innerHTML
        }
    </script>
</body>
  • Related