Javascript 使用 markdown 转换 url 而不是 url 的数组

Javascript transform url with markdown and not into an array of url

我有以下代码,我有一些 urls 有降价(“a”和“b”)和其他没有(“c”和“d”),我必须确保将它们变成字符串数组 url,如下所示。

我怎样才能提出一些建议?

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))

我觉得可以帮到你:

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))