Javascript 如何在粘贴url时将其自动转换为超链接

Javascript 如何在粘贴url时将其自动转换为超链接,javascript,jquery,html,jquery-plugins,Javascript,Jquery,Html,Jquery Plugins,当我尝试在文本框中粘贴url时,如https://stackoverflow.com/它不会自动转换为超链接 我试着使用正则表达式,这是我之前问过的问题。我在这个问题中使用的函数运行良好,但实际上它将替换所有链接,包括标签中的链接(IMG,现有的HREFs) 我不想使用regx如果我使用regx,则在单击任何提交或保存按钮时会发生转换 **当用户在文本框中粘贴url时,应自动将任何链接转换为超链接**** 我用regx试过了 例如: what = "<span>In the task

当我尝试在文本框中粘贴url时,如
https://stackoverflow.com/
它不会自动转换为超链接

我试着使用正则表达式,这是我之前问过的问题。我在这个问题中使用的函数运行良好,但实际上它将替换所有链接,包括标签中的链接(IMG,现有的HREFs)

我不想使用regx如果我使用regx,则在单击任何提交或保存按钮时会发生转换

**当用户在文本框中粘贴url时,应自动将任何链接转换为超链接****

我用regx试过了

例如:

what = "<span>In the task system, is there a way to automatically have any site / page URL or image URL be hyperlinked in a new window?</span><br><br><span>So If I type or copy http://www.stackoverflow.com/&nbsp; for example anywhere in the description, in any of the internal messages or messages to clients, it automatically is a hyperlink in a new window.</span><br><a href="http://www.stackoverflow.com/">http://www.stackoverflow.com/</a><br>    <br><span>Or if I input an image URL anywhere in support description, internal messages or messages to cleints, it automatically is a hyperlink in a new window:</span><br> <span>https://static.doubleclick.net/viewad/4327673/1-728x90.jpg</span><br><br><a href="https://static.doubleclick.net/viewad/4327673/1-728x90.jpg">https://static.doubleclick.net/viewad/4327673/1-728x90.jpg</a><br><br><br><span>This would save us a lot time in task building, reviewing and creating messages.</span>



Test URL's
        http://www.stackoverflow.com/
        https://stackoverflow.com/
        https://stackoverflow.com/
        www.stackoverflow.com
        //stackoverflow.com/
        <a href='https://stackoverflow.com/'>https://stackoverflow.com/</a>";
什么=“在任务系统中,是否有一种方法可以自动将任何站点/页面URL或图像URL超链接到新窗口中?

因此,如果我键入或复制http://www.stackoverflow.com/ 例如,在描述中的任何地方,在任何内部消息或发送给客户端的消息中,它在新窗口中自动成为超链接。


或者,如果我在支持说明、内部消息或cleints消息中的任意位置输入图像URL,它在新窗口中自动成为超链接:
https://static.doubleclick.net/viewad/4327673/1-728x90.jpg




这将为我们节省大量的任务构建时间,查看和创建消息。 测试URL的 http://www.stackoverflow.com/ https://stackoverflow.com/ https://stackoverflow.com/ www.stackoverflow.com //stackoverflow.com/ ";
我试过这个密码

function Linkify(what) {
    str = what; out = ""; url = ""; i = 0;
    do {
        url = str.match(/((https?:\/\/)?([a-z\-]+\.)*[\-\w]+(\.[a-z]{2,4})+(\/[\w\_\-\?\=\&\.]*)*(?![a-z]))/i);
        if(url!=null) {
            // get href value
            href = url[0];
            if(href.substr(0,7)!="http://") href = "http://"+href;

            // where the match occured
            where = str.indexOf(url[0]);

            // add it to the output
            out += str.substr(0,where);

            // link it
            out += '<a href="'+href+'" target="_blank">'+url[0]+'</a>';

            // prepare str for next round
            str = str.substr((where+url[0].length));
        } else {
            out += str;
            str = "";
        }
    } while(str.length>0);
    return out;
}
函数链接(什么){
str=what;out=“”;url=“”;i=0;
做{
url=str.match(/((https?:\/\/)?([a-z\-]+\)*[\-\w]+(\.[a-z]{2,4})+(\/[\w\\\-\?\=\&.]*(?![a-z])/i);
如果(url!=null){
//获取href值
href=url[0];
如果(href.substr(0,7)!=“http:/”)href=“http:/”+href;
//比赛发生在哪里
其中=str.indexOf(url[0]);
//将其添加到输出中
out+=str.substr(0,其中);
//链接它
out+='';
//为下一轮做准备
str=str.substr((其中+url[0].length));
}否则{
out+=str;
str=“”;
}
}而(str.length>0);
返回;
}
这不起作用

当我们将url粘贴到文本框中时,是否有可能自动转换它,就像我们在流上叠加一样?我可以举一些例子吗?

谢谢。

这将有效:

var newStr = str.replace(/(<a href=")?((https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)))(">(.*)<\/a>)?/gi, function () {
    return '<a href="' + arguments[2] + '">' + (arguments[7] || arguments[2]) + '</a>'
});
var newStr=str.replace(/('
});

我回答了这个问题

因此,当用户粘贴richtextbox中的url时,它会自动将任何链接转换为超链接——这里我的richtextbox不是div,而是iframe

如果你的是一个div或任何其他,你可以从这两个问题中得到答案

这是密码

autoAppLink: function (Iframe) {
    var saveSelection, restoreSelection;

    if (window.getSelection && document.createRange) {
        saveSelection = function (containerEl) {
            var range = iframe[0].contentWindow.getSelection().getRangeAt(0);
            var preSelectionRange = range.cloneRange();
            preSelectionRange.selectNodeContents(containerEl);
            preSelectionRange.setEnd(range.startContainer, range.startOffset);
            var start = preSelectionRange.toString().length;

            return {
                start: start,
                end: start + range.toString().length
            }
        };

        restoreSelection = function (containerEl, savedSel) {
            var charIndex = 0, range = document.createRange();
            range.setStart(containerEl, 0);
            range.collapse(true);
            var nodeStack = [containerEl], node, foundStart = false, stop = false;

            while (!stop && (node = nodeStack.pop())) {
                if (node.nodeType == 3) {
                    var nextCharIndex = charIndex + node.length;
                    if (!foundStart && savedSel.start >= charIndex && savedSel.start <= nextCharIndex) {
                        range.setStart(node, savedSel.start - charIndex);
                        foundStart = true;
                    }
                    if (foundStart && savedSel.end >= charIndex && savedSel.end <= nextCharIndex) {
                        range.setEnd(node, savedSel.end - charIndex);
                        stop = true;
                    }
                    charIndex = nextCharIndex;
                } else {
                    var i = node.childNodes.length;
                    while (i--) {
                        nodeStack.push(node.childNodes[i]);
                    }
                }
            }

            var sel = iframe[0].contentWindow.getSelection();
            sel.removeAllRanges();
            sel.addRange(range);
        }
    } else if (document.selection) {
        saveSelection = function (containerEl) {
            var selectedTextRange = document.selection.createRange();
            var preSelectionTextRange = document.body.createTextRange();
            preSelectionTextRange.moveToElementText(containerEl);
            preSelectionTextRange.setEndPoint("EndToStart", selectedTextRange);
            var start = preSelectionTextRange.text.length;

            return {
                start: start,
                end: start + selectedTextRange.text.length
            }
        };

        restoreSelection = function (containerEl, savedSel) {
            var textRange = document.body.createTextRange();
            textRange.moveToElementText(containerEl);
            textRange.collapse(true);
            textRange.moveEnd("character", savedSel.end);
            textRange.moveStart("character", savedSel.start);
            textRange.select();
        };
    }

    function createLink(matchedTextNode) {
        var el = document.createElement("a");
        el.href = matchedTextNode.data;
        el.target = "_blank";
        el.appendChild(matchedTextNode);
        return el;
    }

    function shouldLinkifyContents(el) {
        return el.tagName != "A";
    }

    function surroundInElement(el, regex, surrounderCreateFunc, shouldSurroundFunc) {
        var child = el.lastChild;
        while (child) {
            if (child.nodeType == 1 && shouldSurroundFunc(el)) {
                surroundInElement(child, regex, createLink, shouldSurroundFunc);
            } else if (child.nodeType == 3) {
                surroundMatchingText(child, regex, surrounderCreateFunc);
            }
            child = child.previousSibling;
        }
    }

    function surroundMatchingText(textNode, regex, surrounderCreateFunc) {
        var parent = textNode.parentNode;
        var result, surroundingNode, matchedTextNode, matchLength, matchedText;
        while (textNode && (result = regex.exec(textNode.data))) {
            matchedTextNode = textNode.splitText(result.index);
            matchedText = result[0];
            matchLength = matchedText.length;
            textNode = (matchedTextNode.length > matchLength) ?
                matchedTextNode.splitText(matchLength) : null;
            surroundingNode = surrounderCreateFunc(matchedTextNode.cloneNode(true));
            parent.insertBefore(surroundingNode, matchedTextNode);
            parent.removeChild(matchedTextNode);
        }
    }

    var iframe = Iframe,
        textbox = iframe.contents().find("body")[0];
    var urlRegex = /http(s?):\/\/($|[^ ]+)/;

    function updateLinks() {
        var savedSelection = saveSelection(textbox);
        surroundInElement(textbox, urlRegex, createLink, shouldLinkifyContents);
        restoreSelection(textbox, savedSelection);
    }

    var $textbox = $(textbox);


    $textbox.focus();

    var keyTimer = null, keyDelay = 1000;

    $textbox.keyup(function () {
        if (keyTimer) {
            window.clearTimeout(keyTimer);
        }
        keyTimer = window.setTimeout(function () {

            updateLinks();
            keyTimer = null;
        }, keyDelay);
    });

}
autoAppLink:函数(Iframe){
var保存选择、恢复选择;
if(window.getSelection&&document.createRange){
saveSelection=函数(containerell){
var range=iframe[0].contentWindow.getSelection().getRangeAt(0);
var preselection range=range.cloneRange();
预选范围。选择节点内容(containerell);
预选range.setEnd(range.startContainer,range.startOffset);
var start=preSelectionRange.toString().length;
返回{
开始:开始,
结束:开始+范围.toString().length
}
};
restoreSelection=函数(containeerl、savedSel){
var charIndex=0,range=document.createRange();
range.setStart(containerell,0);
范围。塌陷(真);
var nodeStack=[containerell],node,foundStart=false,stop=false;
而(!stop&&(node=nodeStack.pop()){
if(node.nodeType==3){
var nextCharIndex=charIndex+node.length;
如果(!foundStart&&savedSel.start>=charIndex&&savedSel.start=charIndex&&savedSel.end匹配长度)?
matchedTextNode.splitText(matchLength):空;
surroundingNode=surrounderCreateFunc(matchedTextNode.cloneNode(true));
parent.insertBefore(surroundingNode,matchedTextNode);
parent.removeChild(matchedTextNode);
}
}
变量iframe=iframe,
textbox=iframe.contents().find(“body”)[0];
var urlRegex=/http(s?):\/\/($|[^]+)/;
函数updateLinks(){
var savedSelection=saveSelection(文本框);
surroundInElement(文本框、urlRegex、createLink、shouldLinkifyContents);
恢复选择(文本框,savedSelection);
}
变量$textbox=$(textbox);
$textbox.focus();
var keyTimer=null,keyDelay=1000;
$textbox.keyup(函数(){
if(按键计时器){
窗口清除超时(键定时器);
}
keyTimer=window.setTimeout(函数(){
updateLinks();
keyTimer=null;
},按键延迟);
});
}
以下是我的答案(改进版,包括视频链接)

另见此

const convertLinks=(输入)=>{
让文本=输入;
const linksFound=text.match(/(?:www | https?[^\s]+/g);
常数aLink=[];
如果(linksFound!=null){
for(设i=0;i{return aLink[i].includes('iframe')?item.trim():item}).join(aLink[i]);
}
返回文本;
}
否则{
返回输入;
}

}
对于在2021年发现这个问题并希望有一个很好的功能来完成这一切的人,我在这里找到了一个:

函数链接(inputText){
变量replacedText、replacePattern1、replacePattern2、replacePattern3;
//以http://、https://或ftp开头的URL://
replacePattern1=/(\b(https?| ftp):\/\/[-A-Z0-9+&@#\/%?=~+!:,.;]*[-A-Z0-9+&@#\/%=~_
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" 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 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;
}