-1

I have below description, which I am trying to replace the links in href props with signed s3 links on the backend without DOM

So, I need to first loop over all the matching s3 links and replace it with signed one.

The problem is It replaces other parts as well. It doesn't know when to end the matching.

Here is what I am trying to do,

  1. Collect all the links
  2. Filter links which has s3 related keyword
  3. replace them with signed s3 link

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)

The result I get is,

"<h3>Introduction Session</h3><p>Monday, March 3, 2021 11:00AM - 01:00PM</p> 
    Click <a href='https://signed-s3-link.com"
mplungjan
  • 169,008
  • 28
  • 173
  • 236
confusedWarrior
  • 938
  • 2
  • 14
  • 30
  • 1
    Regex processing of HTML is a [bad approach](https://stackoverflow.com/a/1732454/3136474). Couldn't you replace the links in the DOM by selecting `a` tags instead of replacing them using regex in the HTML code? – Dinei Nov 29 '21 at 14:30

1 Answers1

0

I was wrong with the link matching regex, this seems to work for my case.

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)
confusedWarrior
  • 938
  • 2
  • 14
  • 30