【问题标题】:Replace links with some other link in a text用文本中的其他链接替换链接
【发布时间】:2021-11-29 14:25:53
【问题描述】:

我有以下描述,我试图用签名的 s3 链接替换 ​​href 道具中的链接在没有 DOM 的后端

所以,我需要先遍历所有匹配的 s3 链接并将其替换为已签名的链接。

问题是它也替换了其他部分。它不知道何时结束匹配。

这就是我想要做的,

  1. 收集所有链接
  2. 过滤具有 s3 相关关键字的链接
  3. 用签名的 s3 链接替换它们

function replaceNonSignedS3WithSignedLink(text) {
  const urlRegex = /(https?:\/\/[^\s]+)/g;
  return text.replace(urlRegex, function(url) {
    return 'https://signed-s3-link.com';
  })
  // or alternatively
  // return text.replace(urlRegex, '<a href="$1">$1</a>')
}
const desc = `<h3>Introduction Session</h3><p>Monday, March 3, 2021 11:00AM - 01:00PM</p> 
    Click <a href='https://example.s3.amazonaws.com/assets/bio.pdf'>here</a>`;

const result = replaceNonSignedS3WithSignedLink(desc);

console.log(result)

我得到的结果是,

"<h3>Introduction Session</h3><p>Monday, March 3, 2021 11:00AM - 01:00PM</p> 
    Click <a href='https://signed-s3-link.com"

【问题讨论】:

  • 对 HTML 的正则表达式处理是一个bad approach。您不能通过选择a 标记来替换 DOM 中的链接,而不是在 HTML 代码中使用正则表达式替换它们吗?

标签: javascript regex


【解决方案1】:

我的链接匹配正则表达式有误,这似乎适用于我的情况。

let i = 0;
function urlify(text) {
  var urlRegex = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
  return text.replace(urlRegex, function(url) {
    if (url.includes('s3')) return 'https://signed-s3-link.com' + ++i; // I can process individual link here
    return url;
  })
}

var text = `<h3>Introduction Session</h3><p>Monday, March 3, 2021 11:00AM - 01:00PM</p> 
    Click <a href='https://example.s3.amazonaws.com/assets/bio.pdf'>here</a> <a href = 'https://hello.com'>Hi</a>`;
var html = urlify(text);

console.log(html)

【讨论】:

  • 我以为你只想更改包含 s3 的链接?
  • 这可以通过if (url.includes('s3')){ // update the link}轻松实现
  • 我知道。就像我在回答中所做的那样。
  • @mplungjan 限制是,我忘了提,它正在后端处理。所以,没有 DOM 可以访问。
  • 所以这是stackoverflow.com/questions/37684/…的直接骗子
猜你喜欢
  • 1970-01-01
  • 2014-08-01
  • 1970-01-01
  • 2018-03-22
  • 1970-01-01
  • 1970-01-01
  • 2017-10-15
  • 1970-01-01
  • 2011-03-06
相关资源
最近更新 更多