Home > Back-end >  Javascript transform url with markdown and not into an array of url
Javascript transform url with markdown and not into an array of url

Time:03-05

I have the following code, I have some urls with markdown ("a" and "b") and others without ("c" and "d"), I have to make sure to turn them into an array of string url, as seen below.

How can I make some suggestions?

let a = "a [this](https://upload.wikimedia.org/wikipedia/commons/thumb/7/7e/T._rex_infection.png/440px-T._rex_infection.png)!"
let b = "b [this](https://upload.wikimedia.org/wikipedia/commons/thumb/7/7e/T._rex_infection.png/440px-T._rex_infection.png)! - [this](https://upload.wikimedia.org/wikipedia/commons/thumb/a/a9/Mosasaurus-Skelett.jpg/440px-Mosasaurus-Skelett.jpg)"
let c = "https://upload.wikimedia.org/wikipedia/commons/thumb/7/7e/T._rex_infection.png/440px-T._rex_infection.png"
let d = ["https://upload.wikimedia.org/wikipedia/commons/thumb/7/7e/T._rex_infection.png/440px-T._rex_infection.png", "https://upload.wikimedia.org/wikipedia/commons/thumb/a/a9/Mosasaurus-Skelett.jpg/440px-Mosasaurus-Skelett.jpg"]
let e = "['https://upload.wikimedia.org/wikipedia/commons/thumb/c/c9/Tyrannosaurus_rex_Sue_at_FMNH.jpg/440px-Tyrannosaurus_rex_Sue_at_FMNH.jpg']"
let f = "['https://upload.wikimedia.org/wikipedia/commons/thumb/c/c9/Tyrannosaurus_rex_Sue_at_FMNH.jpg/440px-Tyrannosaurus_rex_Sue_at_FMNH.jpg','https://upload.wikimedia.org/wikipedia/commons/thumb/b/bc/Mosasaurus_beaugei_34.JPG/440px-Mosasaurus_beaugei_34.JPG']"


const url = (text, autoMatch = false) => {
  if (!autoMatch) return [text].flat();
  if (autoMatch) {
    const match = text.match(/\((.*)\)/);
    console.log("*", match, ";")
    if (match === null) return "";
    return match[1] || "";
  }
};

console.log(url(a, true))
console.log(url(b, true))
//console.log(url(c))
//console.log(url(d))

CodePudding user response:

I think it can helps you:

const getLinksFromString = (text) => text.match(/https[^ '")]*/gi);

const getLinks = (data) => {
    switch (typeof data) {
        case 'string':
            return getLinksFromString(data);
        case 'object':
            const links = [];
            
            for (text of data) {
                links.push(...getLinksFromString(text));
            }
            
            return links;
    }
}

const data = "b [this](https://upload.wikimedia.org/wikipedia/commons/thumb/7/7e/T._rex_infection.png/440px-T._rex_infection.png)! - [this](https://upload.wikimedia.org/wikipedia/commons/thumb/a/a9/Mosasaurus-Skelett.jpg/440px-Mosasaurus-Skelett.jpg)"

console.log(getLinks(data))

  • Related