2014-06-11 52 views
2

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

我试过使用正则表达式,这是我之前询问的Question。我在这个问题中使用的函数可以正常工作,但实际上它会替换所有链接,包括标签中的链接(IMG,现有的A HREF)。

我不想使用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>"; 

我试过这个代码

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; 
} 

fiddle无法运作

是否有可能将其自动转换,当我们在文本框中粘贴URL就像我们在栈上的流动得到我可以有一些例子吗?

谢谢。

+1

你应该张贴,你有什么第一次尝试.. ! {CODE} –

+1

将网址粘贴到哪里? – ZiNNED

+0

@RajaprabhuAravindasamy我试过在这个问题中使用正则表达式http://stackoverflow.com/questions/23759302/how-to-detect-links-with-out-anchor-element-in-a-plain-text我提到,在上面的问题 – dhee

回答

2

Autolink URL in ContentEditable Iframe

在这个问题上我回答

,这样当用户粘贴在一个RichTextBox一个URL,它会自动转换任何超链接的链接 - 在这里我的richtextbox不是一个div它的iframe

如果你的是一个div或任何其他可从以下两个问题

Autolink URL in contenteditablejQuery: Convert text URL to link as typing

得到答案,这里的代码

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); 
    }); 

} 
4

这将工作:

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

JSFiddle hereRegexr

+0

Vinz243非常感谢,如果这个作品,我真的很感谢你 – dhee

+0

Vinz243看到这[[小提琴](http ://jsfiddle.net/LgNtR/6/)这dosent与正则表达式工作,我想要自动转换它,当我贴上一个url – dhee

+0

打开你broser控制台,你会意识到,你忘了包括jQuery ... – Vinz243

相关问题