1

Is it possible to only store URLs of currently selected text?

This saves selected text on page

var selectedText = window.getSelection().toString(); 

and this saves ALL hyperlinks

var links = document.links; 

Edit:
This returns null:

var data=new Object(); data.selectedText = window.getSelection(); console.log(data.selectedText.outerHTML); 
2
  • 1
    You'd have to run a regular expression on window.getSelection() to pick out links. Commented Sep 4, 2013 at 23:48
  • How can i extract data from window.getSelection()? tried .outerHTML but it's null Commented Sep 5, 2013 at 12:48

2 Answers 2

1

If you only want to get links that are in "a" tags you can just do something like this:

function getLinksFromSelection() { if (window.getSelection) { var selection = window.getSelection(); if (selection.rangeCount > 0) { var range = selection.getRangeAt(0); var div = document.createElement('DIV'); div.appendChild(range.cloneContents()); var links = div.getElementsByTagName("A") for (var i=0; i < links.length; i++) { console.log(links[i].href); } } } 

If you also want to take into account a selection that is contained within a link (i.e. the link is a parent node to the selection) then you'd add something like this:

var alink = range.commonAncestorContainer; if (alink.nodeType == 3) { // if text node then get parent alink = alink.parentNode; } if (alink.tagName === 'A') { console.log(alink.href) } 

Here's the fiddle: http://jsfiddle.net/ESr3C/

Sign up to request clarification or add additional context in comments.

Comments

0
function getLinks() { var selectedText = window.getSelection().toString(); regex = new RegExp(/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)/gim); var result; while((result = regex.exec(selectedText)) !== null) { console.log(result[1]) } } 

1 Comment

This writes the found links to the console, but you can always store in an array.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.