素材牛VIP会员
如何实时替换编辑器内的文本成为链接?
 邓***一  分类:Node.js  人气:1455  回帖:2  发布于6年前 收藏

例如知乎编辑器内,如果粘贴了一段网址,会自动转换为链接。
stack 上找到的代码不知道该如何用,大家可以看看。

function replaceURLWithHTMLLinks(text) {
    var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
    return text.replace(exp,"<a href='$1'>$1</a>"); 
   }

是监视 keyup 来替换的吗?希望得到大家的解答!谢谢!

*** // Update:2013-12-09 :***

编辑器为 <div contenteditable="true"></div>

讨论这个帖子(2)垃圾回帖将一律封号处理……

Lv5 码农
面***笑 JAVA开发工程师 6年前#1
  linkify: function(inputText) {
        var replacedText, replacePattern1, replacePattern2, replacePattern3;
        var originalText = inputText;
        //URLs starting with http://, https://, file:// or ftp://
        replacePattern1 = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gi;
        //URLs starting with "www." (without // before it, or it'd re-link the ones done above).
        replacePattern2 = /(^|[^\/f])(www\.[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gi;
        //Change email addresses to mailto:: links.
        replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gi;
        //If there are hrefs in the original text, let's split
        // the text up and only work on the parts that don't have urls yet.
        var count = originalText.match(/<a href/g) || [];
        if (count.length > 0) {
            var combinedReplacedText;
            //Keep delimiter when splitting
            var splitInput = originalText.split(/(<\/a>)/g);

            for (i = 0; i < splitInput.length; i++) {
                if (splitInput[i].match(/<a href/g) == null) {
                    splitInput[i] = splitInput[i].replace(replacePattern1, '<a href="$1" target="_blank">$1</a>').replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>').replace(replacePattern3, '<a href="mailto:$1">$1</a>');
                }
            }
            combinedReplacedText = splitInput.join('');
            return combinedReplacedText;
        } else {
            replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');
            replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');
            replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');
            return replacedText;
        }
    },

对一段文本,可重复运行。

Lv3 码奴
18***30 Linux系统工程师 6年前#2

不推荐用keyup事件,因为它对非键盘操作的动作没反应,比如鼠标粘贴进来一个网址。这时候需要用onPropertyChange事件,能够对textarea内的属性值的变化产生动作。

另外,正则部分推荐最后加一个空格判定,也就是URL+空格才解析为链接形式,如果是之前的匹配的话会造成死循环。

http://jsfiddle.net/5kmqe/1/

 文明上网,理性发言!   😉 阿里云幸运券,戳我领取