当前位置:Gxlcms > PHP教程 > javascript-如何实时替换编辑器内的文本成为链接?

javascript-如何实时替换编辑器内的文本成为链接?

时间:2021-07-01 10:21:17 帮助过:18人阅读

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

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

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

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

编辑器为

回复内容:

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

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

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

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

编辑器为

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

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

http://jsfiddle.net/5kmqe/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(/ 0) {
            var combinedReplacedText;
            //Keep delimiter when splitting
            var splitInput = originalText.split(/(<\/a>)/g);

            for (i = 0; i < splitInput.length; i++) {
                if (splitInput[i].match(/$1').replace(replacePattern2, '$1$2').replace(replacePattern3, '$1');
                }
            }
            combinedReplacedText = splitInput.join('');
            return combinedReplacedText;
        } else {
            replacedText = inputText.replace(replacePattern1, '$1');
            replacedText = replacedText.replace(replacePattern2, '$1$2');
            replacedText = replacedText.replace(replacePattern3, '$1');
            return replacedText;
        }
    },

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

人气教程排行