How to detect Links with out anchor element in a plain text

后端 未结 2 1703
轻奢々
轻奢々 2021-01-14 07:33

If user enters his text in the text box and saves it and again what\'s to add some more text he can edit that text and save it if required.

Firstly if user enters th

相关标签:
2条回答
  • 2021-01-14 08:06

    A more simple solution is probably to strip the links which you created (so the user gets exactly what they typed when they click "Edit" again).

    Another idea is to split the string at </a>. That gives you a list of strings which all end with an anchor element (except the last one). Iterate over this list, cut away the part after the last <a, linkify.

    0 讨论(0)
  • 2021-01-14 08:08

    here is a regex where you select all the links without having anchors

    (?:(?:http(?:s)?(?:\:\/\/))?(?:www\.)?(?:\w)*(?:\.[a-zA-Z]{2,4}\/?))(?!([\/a-z<\/a>])|(\'|\"))
    

    Here is a RegExFiddle (updated 14:41)

    quit a lil difficult task because in javascript you don't have a preceded by statement. :)

    EDIT1: Now it detects...

    http://www.abc.xy
    http://abc.xy
    https://www.abc.xy
    https://abc.xy
    www.abc.xy
    abc.xy
    

    EDIT2:

    Here is it a little shorted and the usage fiddle

    Regex

    /((http(s)?(\:\/\/))?(www\.)?(\w)*(\.[a-zA-Z]{2,4}\/?))(?!([\/a-z<\/a>])|(\'|\"))/g
    

    function

    function Linkify(str) {
        var newStr =  str.replace(/((http(s)?(\:\/\/))?(www\.)?(\w)*(\.[a-zA-Z]{2,4}\/?))(?!([\/a-z<\/a>])|(\'|\"))/g,'<a href="$1">$1</a>');
        return newStr;
    }
    
    var newData = Linkify(data);
    

    WORKING JS-FIDDLE

    EDIT 1.000.000 :D

    /((http(s)?(\:\/\/))?(www\.)?([\w\-\.\/])*(\.[a-zA-Z]{2,3}\/?))(?!(.*a>)|(\'|\"))/g
    

    this solves your problem now.

    the only problem you will run in here is, 4 letters after a dot is not selected. e.g .info if you want them selected than change {2,3} to {2,4} BUT be carefully... if someone adds a text like my name is.john than is.john will be translated to a link.

    0 讨论(0)
提交回复
热议问题