Skip to content Skip to sidebar Skip to footer

Removing The Links From Reddit Comments

I am reading the comments from under reddit posts. Some of the comments have links, that I would like to get rid of. Example (input): This is a [pic](https://i.imgur.com/yKmUMJD.jp

Solution 1:

I saw you had posted a similar question earlier. Now you have also posted what you have tried... looks like you are struggling with this one.

Here's what I would do:

const str = "This is a [pic](https://i.imgur.com/yKmUMJD.jpg), [this](http://www.google.com) is a link";

const tags = str.match(/\[.*?(?=\]\((.*?)\))/g).map(x => x.substring(1));
const newString = str.replace(/\[.*?\]\(.*?\)/g, () => {
  return tags.shift();
});

console.log(newString)

First step is to find all of the marked up text. In other words, everything wrapped in []. In your example above, this will yield the array [pic, this].

Then, we need to replace the whole url bbcode (i.e the [xxx](http://url)) with each of our matches above. We treat our array as a queue, and remove each result from the array with shift() once we've used it.

Of course, this solution isn't fool-proof. It won't handle the corner-case in which any of the characters ()[] are part of either the markup or the URL itself.

Post a Comment for "Removing The Links From Reddit Comments"