JavaScript如何从所选文本中提取链接
JavaScript How to extract link from selected text
我正在寻找如何使用window.getSelection
和document.selection
从所选文本中提取url的解决方案。
要选择的文本外观:
<p>Lorem Ipsum is <a href="http://example.com">simply <b>dummy</b> text</a> of the printing and typesetting industry.</p>
要提取链接的选定文本(由用户选择):
选项1(包括文本和标签之间的文本):
Ipsum is simply dummy text of
选项2(选择链接的文本和片段):
Ipsum is simply
函数应为return http://example.com
很难编写跨浏览器功能。请参阅如何将处理程序绑定到窗口上的选择更改?。
我们应该捕获一些事件,如mousedown
、mouseup
、touchstart
、touchend
。这些事件的组合可能很好。
function addEvent(elem, event, func) {
if (elem.addEventListener) {
elem.addEventListener(event, func, false);
} else {
elem.attachEvent('on' + event, func);
}
}
接下来是使用window.getSelection
或document.selection
的getSelectedHTML()
。
function getSelectedHTML(event) {
// http://www.w3.org/TR/2000/REC-DOM-Level-2-Traversal-Range-20001113/ranges.html
var range = window.getSelection ? window.getSelection() /* W3C */
: document.getSelection ? document.getSelection() /* redundant? */
: document.selection ? document.selection.createRange() /* IE */
: null;
if (range) {
if (range.getRangeAt) {
range = range.getRangeAt(0);
} else if (range.setStart) { // Safari 1.3
// Create range by itself
range.setStart(range.anchorNode, range.anchorOffset);
range.setEnd(range.focusNode, range.focusOffset);
} else {
// IE is already reange
}
var html = null, link = null;
if (range.cloneContents) {
var dummy = document.createElement('div');
dummy.appendChild(range.cloneContents());
html = dummy.innerHTML;
} else {
html = range.htmlText; /* IE */
}
if (html) {
link = html.match(/<a.*?href's*?=['"](.*?)['"]/);
return link ? link[1] : null;
}
}
return null;
}
应该检查此代码,尤其是在旧浏览器中。
这是样品小提琴:http://jsfiddle.net/tokkonoPapa/CQ63a/
如果我误解了这个问题,我很抱歉,但这是我的建议。
有一个函数,并将选定的HTML传递给它,让它像这样处理它。
function FindLink(str){
// str='<p>Lorem Ipsum is <a href="http://example.com">simply <b>dummy</b> text</a> of the printing and typesetting industry.</p>';
// we get the index of the beginning of the <a> tag
var n = str.indexOf("<a") ;
// we find the href property of the <a> element, starting from the <a we found
var n2 = str.indexOf("href='"", n) + 6;
// we find the end of the href property
n3 = str.indexOf("'">",n2);
// we find the substring starting at the beginning of the link and going for however many characters the link is
link = str.substr(n2,n3-n2);
return link;
}
我希望这有帮助!
相关文章:
- 是否可以自动拉取“随机”;标签“;从一长串文本中提取
- 使用BeautifulSoup从Javascript中提取文本以获得关注者数量
- 使用提取文本webpack插件时出现意外字符
- 有没有一种方法可以从两个标签之间提取文本,并以我选择的格式输出
- 更换163;使用javascript从html文本区域中提取字符
- 正则表达式,用于从html格式的字符串中提取文本
- 如何从由“”分隔的字符串中提取最后一个文本|&”;
- jquery电子邮件提取器实时从文本区域
- 使用JavaScript从HTML字符串中提取文本
- 如何使用JQuery从文本区域内容中提取属性
- Tinymce-4:仅从链接中提取文本
- 在输入字段之前提取表格单元格中的文本
- Javascript FileReader:提取文本
- 如何使用正则表达式从javascript/jquery中的属性值中提取文本
- 如何从字符串中提取特定文本.最困难的部分是所需的文本会定期更改
- 从JavaScript中提取文本
- jQuery文本提取方法不从HTML中提取文本
- 在Javascript中将字符串文本提取为常量是一种最佳实践吗
- 通过功能和文本提取在web浏览器中突出显示
- 将大括号内的所有文本提取到字符串数组中