Regex之后,超链接正在破裂

时间:2016-09-12 09:31:54

标签: javascript regex

向客户端发送新消息并在客户端接收后,我通过确定超链接并使其可点击的功能传递给客户端。问题是,如果字符串包含类似此this is the link http://linktosomwhere.com?ref=myname to somewhere的链接,则会解析链接错误并使其如下所示:this is the link <a...>http://linktosomwhere.com</a> ?ref=myname to somewhere。因此它打破了链接,增加了它不应该存在的空间。正如我之前提到的,使用此功能的一切都在客户端进行:

&#13;
&#13;
function linkify(inputText) {
    var replacedText, replacePattern1, replacePattern2, replacePattern3;

    //URLs starting with http://, https://, or ftp://
    replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
    replacedText = inputText.replace(replacePattern1, '<a href="$1" rel="nofollow" target="_blank">$1</a>');

    //URLs starting with "www." (without // before it, or it'd re-link the ones done above).
    replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
    replacedText = replacedText.replace(replacePattern2, '$1<a rel="nofollow" href="http://$2" target="_blank">$2</a>');

    //Change email addresses to mailto:: links.
    replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
    replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');

    return replacedText;

    }
console.log(linkify('this is the link http://linktosomwhere.com?ref=myname to somewhere'));
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

我重新创建了功能

linkify = string => {
        // Set addHTTPS to blank string
        let addHTTPS = '';
        /* 
        Regex checks if URL starts with "www." 
        If so addHTTPS is set to https://.
        */
        if (/(?=.+)\s(https:\/\/|mailto:|www\.|ftp:\/\/|http:\/\/)(?=\S+\?ref=.+$)/.exec(string)[0] == " www.") {
            addHTTPS = "https://";
        };
        // returns the replaced version of the string and automatically adds https:// if necessary because of the if statement above
        return (string.replace(/^(.+)\s(https:\/\/|mailto:|www\.|ftp:\/\/|http:\/\/)(\S+)\?ref=(.+)$/,
            '<a rel="nofollow" href="${addHTTPS}$2$3" ref="$4"> $1 </a>'));
    
    };
    
    document.write(linkify("Go to Google www.google.com?ref=google"))

此处介绍正则表达式的工作方式:

/ => Start of regex

^ => Assert start of match

(.+) => capture group for any string of characters

\s => whitespace character

(https:\/\/|mailto:|www\.|ftp:\/\/|http:\/\/) => capture group for start of url that looks for "https://" or "http://" or "mailto:" or "www."

(\S+) => capture group for any string of characters that is not a space

?ref= => look for ref attribute

(.+) => any string of characters for the ref attribute

$ => Assert end of match

/ => End of regex