【问题标题】:Replace all the relative path with absolute path and ignore the paths that is already absolute using regex用绝对路径替换所有相对路径,并使用正则表达式忽略已经是绝对的路径
【发布时间】:2021-03-26 11:57:26
【问题描述】:

我有以下字符串,

Some text ![test1](assets/image1.png) \n some text ![test2](https://example.com/assets/image2.png) some other text \n ![test3](assets/image3.png)

我想将所有相对图像路径(即 assets/image1.png 替换为 https://example.com/assets/image1.pngassets/image3.png 相同)。但是我们需要忽略https://example.com/assets/image2.png,因为它已经是绝对路径了。

到目前为止,我已经能够做到以下几点,

const getImagesWithAbsolutePath = (text, absolutePathPrefix) => {
    if (!text) return ''
    const regex = /(\!\[.*\]\()(.*)(\))/g
    return text.replace(regex, '$1' + absolutePathPrefix + '/$2?raw=true$3')
}

myText = "Some text ![test1](assets/image1.png) \n some text ![test2](https://example.com/assets/image2.png) some other text \n ![test3](assets/image3.png)";

myDomain = "https://example.com";

console.log(getImagesWithAbsolutePath(myText, myDomain));

如你所见,输出是,

 Some text ![test1](https://example.com/assets/image1.png?raw=true) 
 some text ![test2](https://example.com/https://example.com/assets/image2.png?raw=true) some other text 
 ![test3](https://example.com/assets/image3.png?raw=true)

但我需要的结果是,

Some text ![test1](https://example.com/assets/image1.png?raw=true) 
some text ![test2](https://example.com/assets/image2.png?raw=true) some other text 
![test3](https://example.com/assets/image3.png?raw=true)

【问题讨论】:

  • 使用惰性点 (/(\!\[.*?\]\()(.*?)(\))/g) 或否定字符类。
  • @WiktorStribiżew 谢谢,它不起作用。返回相同的结果。
  • 除了这个问题不重复。我已经看到了这个问题,它实际上并没有帮助。谢谢。
  • 对,你需要随意匹配主机。
  • 无论如何,您确实需要在模式中使用惰性点/否定字符类来处理同一行上的多个匹配项。起初我被骗了,因为我没有在您的示例字符串文字中发现所有 \n。将您处理的文字也添加到问题中是个好主意,但代码也总是很好,当然。

标签: javascript regex string


【解决方案1】:

你需要

  • 使用惰性点/否定字符类确保您的 (/)[/] 分隔符不匹配
  • 可选地匹配 myDomain 主机部分,以便在您将其添加回来时可以将其删除:

const myDomain = "https://example.com";
const getImagesWithAbsolutePath = (text, absolutePathPrefix) => {
    if (!text) return ''
    const regex =  new RegExp("(!\\[.*?]\\()(?:" + myDomain.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + "/*)?(.*?)(\\))", "g")
    return text.replace(regex, '$1' + absolutePathPrefix + '/$2?raw=true$3')
}

let myText = "Some text ![test1](assets/image1.png) \n some text ![test2](https://example.com/assets/image2.png) some other text \n ![test3](assets/image3.png)";

console.log(getImagesWithAbsolutePath(myText, myDomain));

请参阅regex demo

详情

  • (!\[.*?]\() - 第 1 组:![,除换行符之外的任何零个或多个字符尽可能少,](
  • (?:https:\/\/example\.com\/*)? - https://example.com 字符串的可选出现,然后是零个或多个 / 字符
  • (.*?) - 第 2 组:除换行符之外的任何零个或多个字符尽可能少
  • (\)) - 第 3 组:) 字符。

注意:如果您碰巧在absolutePathPrefix (myDomain) 中有$ + 数字,则需要替换为'$1' + absolutePathPrefix.replace(/\$/g, '$$$$') + '/$2?raw=true$3'

【讨论】:

  • 非常感谢。起初,我不确定它是如何工作的。你的解释很有帮助。赞一个!
猜你喜欢
  • 1970-01-01
  • 2015-11-13
  • 1970-01-01
  • 2023-03-25
  • 1970-01-01
  • 1970-01-01
  • 2012-01-11
  • 2010-09-15
  • 2013-04-17
相关资源
最近更新 更多