【问题标题】:JQUERY - search for ".com" and save URL as variableJQUERY - 搜索“.com”并将 URL 保存为变量
【发布时间】:2017-04-11 06:28:22
【问题描述】:

我正在为 wordpress 使用 PDF 到 HTML 插件,它为每个页面生成一个画布和一个文本层。我需要在 PDF 中使任何 URL 都可点击,因此我正在尝试编写一个脚本来检测和 URLS(使用 .com 作为标识符,稍后我可能会添加)。

在这个阶段我需要帮助的只是将完整的 URL 捕获为变量,而不仅仅是包含“.com”的 div

我目前有这个脚本,但是我需要用找到的 URL 替换“http://test.com”。

$('div:contains(".com")').each(function () {
    $(this).addClass('contains-url');
    console.log('found div containing a URL');

    $(this).attr('href','http://test.com');

});


$('.contains-url').click(function(){
  console.log('clicked - this will open in a new tab');
    window.open($(this).attr("href"), '_blank');
});
div{
border: 1px solid #000; padding: 5px; width: 100%; margin-bottom: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
This div does not contain a URL
</div>

<div>
This div contains URL http://loremipsum.com
</div>

非常感谢任何帮助

【问题讨论】:

  • 我还应该补充一点,上面的代码是我正在编辑的一个非常简单的版本,但是它以相同的方式工作
  • 试试我的答案很简单

标签: jquery variables search


【解决方案1】:

您可以从此link使用findUrls($(this).text())

$('div:contains(".com")').each(function() {
  $(this).addClass('contains-url');
  console.log('found div containing a URL');
  var url = findUrls($(this).text())
  $(this).attr('href', url);
console.log($(this).attr('href'))
});


$('.contains-url').click(function() {
  console.log('clicked - this will open in a new tab');
  window.open($(this).attr("href"), '_blank');
});

function findUrls(text) {
  var source = (text || '').toString();
  var urlArray = [];
  var url;
  var matchArray;

  // Regular expression to find FTP, HTTP(S) and email URLs.
  var regexToken = /(((ftp|https?):\/\/)[\-\w@:%_\+.~#?,&\/\/=]+)|((mailto:)?[_.\w-]+@([\w][\w\-]+\.)+[a-zA-Z]{2,3})/g;

  // Iterate through any URLs in the text.
  while ((matchArray = regexToken.exec(source)) !== null) {
    var token = matchArray[0];
    urlArray.push(token);
  }

  return urlArray;
}
div {
  border: 1px solid #000;
  padding: 5px;
  width: 100%;
  margin-bottom: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  This div does not contain a URL
</div>

<div>
  This div contains URL http://loremipsum.com
</div>

【讨论】:

  • 感谢您的快速回复,我会试试这个,但看起来这会满足我的需要,所以我会将您的答案标记为正确:)
  • 嘿,Carsten,它可以工作,但目前只保存电子邮件地址。它不会保存正常的 URL。看控制台截图:pasteboard.co/2VhoXsTJZ.jpg红色区域是正常URL生成的空格
  • 我认为是因为它正在搜索 http?可以只搜索.com吗?并非所有 URL 都包含 http,大多数包含 www 但不是全部
  • 好的,我已经调整它来搜索 www 以及 ftp 和 http。再次感谢您:) 效果很好!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多