PasiB
PasiB

Reputation: 107

Node.js get all occurrences of a substring in a string

I have a string in Node.js Runtime e.g

var content = "my content contain some URL like https://this.me/36gD6d3 or https://this.me/39Jwjd";

How can I read each https://this.me/36gD6d3 and https://this.me/39Jwjd to replace it with another URL?

A forEach loop or something similar would be best. :-)

What I need is to make a request to each of that URL to get the real URL behind the shorten URL. That's not the problem.


Before and after each of that URLs is neither a whitespace or a .. Domain https://this.me/ is constant but the IDs 39Jwjd, 36gD6d3 are changing.

Looking forward to your answers! :)

Upvotes: 2

Views: 753

Answers (2)

blex
blex

Reputation: 25634

If you want your replace to be asynchronous (which I'm guessing is the case when you lookup the full URL), you could do something like this:

(async () => {
  const str = "my content contain some URL like https://this.me/36gD6d3 or https://this.me/39Jwjd",
        res = await replaceAllUrls(str);
  console.log(res);
})();

function replaceAllUrls(str) {
  const regex   = /https?:\/\/this\.me\/[a-zA-Z0-9_-]+/g,
        matches = str.match(regex) || [];

  return Promise.all(matches.map(getFullUrl)).then(values => {
    return str.replace(regex, () => values.shift());
  });
}

function getFullUrl(u) {
  // Just for the demo, use your own
  return new Promise((r) => setTimeout(() => r(`{{Full URL of ${u}}}`), 100));
  // If it fails (you cannot get the full URL),
  // don't forget to catch the error and return the original URL!
}

Upvotes: 1

pavi2410
pavi2410

Reputation: 1285

You can use regex to find occurrences of this URL.

var content = "my content contain some URL like https://this.me/36gD6d3 or https://this.me/39Jwjd";
console.log(content.match(/https:\/\/this\.me\/[a-zA-Z0-9]+/g))

This outputs:

[
  "https://this.me/36gD6d3",
  "https://this.me/39Jwjd"
]

In order to replace the found occurrences, use replace() function.

var content = "my content contain some URL like https://this.me/36gD6d3 or https://this.me/39Jwjd";
console.log(content.replace(/https:\/\/this\.me\/[a-zA-Z0-9]+/g, "<Replaced URL here>"))

Output:

my content contain some URL like <Replaced URL here> or <Replaced URL here>

If you want to replace the occurrences depending on the previous value, you could either use substitution or pass replacement function as the second argument.

Learn more on String.prototype.replace function at MDN

Upvotes: 2

Related Questions