我有一个带有以下链接的降价文本文件:
[Text](https://docs.google.com/document/d/unique-doc-id-here/edit)
or
[Text2](https://docs.google.com/document/d/unique-doc-id-here")
我想通过取unique-doc-id-here
将整个href
替换为另一个,将其传递给将返回新 href 的函数,因此结果我的 url 看起来像这样:
[Text](https://new-url-here.com/fragment-unique-id)
or
[Text2](https://new-url-here.com/fragment-unique-id)
我认为我的问题是选择unique-doc-id-here
,我认为我必须为此使用正则表达式。
因此,解决方案可能如下所示:
text.replace(/https://docs.google.com/document/d/(.*?)*/gm, (x) =>
this.getNewHref(x)
);
但是,正则表达式似乎看起来不太正确,因为它在所有情况下都不多。有什么想法如何解决吗?
下面是一个输入文本示例:
# Title
Text text text.
Text 1 text 1 text 1, abc.
More text
Bullet points
- [abc]
- [bla]
- [cba]
## Title 2
More text:
- A
- B
- C
- D
Text text text text [url1](https://docs.google.com/document/d/2x2my-DRqfSidOsdve4m9bF_eEOJ7RqIWP7tk7PM4qEr) text.
**BOLD.**
## Title
Text2 text1 text3 text
[url2](https://docs.google.com/document/d/4x2mrhsqfGSidOsdve4m9bb_wEOJ7RqsWP7tk7PMPqEb/edit#bookmark=id.mbnek2bdkj8c) text.
More text here
[bla](https://docs.google.com/document/d/6an7_b4Mb0OdxNZdfD3KedfvFtdf2OeGzG40ztfDhi5o9uU/edit)
我已经尝试过这个正则表达式w+://.*?(?=s)
但它确实选择了最后一个)
符号
我已经应用了一个建议的解决方案,@The fourth bird
:
function getNewHref(id: string) {
const data = getText();
const element = data.find((x: any) => x.id === id);
if(element?.url) {
return element.url;
} else {
return 'unknown-url'
}
}
<小时 />data = data.replace(
/[[^][]*](https?://docs.google.com/document/d/([^s\/)]+)[^s)]*)/gm,
(x, g1) => getNewHref(g1)
);
问题是替换功能替换了整个东西,所以[...](...)
的东西变得./new-url
或unknown-url
,但需要我[original text](new result)
可以使模式更具体,然后使用组 1 值。
([[^][]*]()https?://docs.google.com/document/d/([^s\/)]+)[^s)]*)
零件中的模式匹配:
([[^][]*]()
捕获组 1,使用否定字符类从[...](
匹配https?://docs.google.com/document/d/
匹配网址的前导部分(
捕获组 2[^s\/)]+
匹配除- 空格字符、
或
/
以外的 1+ 个字符
- 空格字符、
)
关闭组 1[^s)]*
匹配除空格字符或)
以外的可选字符)
比赛)
正则表达式演示
例如,一个快乐的案例场景,其中所有要替换的键都存在(请注意,您可以省略/m
标志,因为模式中没有锚点)
const text = "[Text](https://docs.google.com/document/d/unique-doc-id-here/edit)";
const regex = /([[^][]*]()https?://docs.google.com/document/d/([^s\/)]+)[^s)]*)/g;
function getNewHref(id) {
const replacements = {
"unique-doc-id-here": `https://docs.google.com/document/d/${id}`
}
return replacements[id];
}
const replacedText = text.replace(regex, (x, g1, g2) => g1 + getNewHref(g2)) + ")";
console.log(replacedText);
您可以通过使用RegEx
从字符串中获取href
链接,然后使用正斜杠将其拆分来实现此目的。
试试这个(描述性注释已添加到下面的代码片段中):
const text = '<a href="https://docs.google.com/document/d/unique-doc-id-here/edit">Text</a>';
// Get the href link using regex
const link = text.match(/"([^"]*)"/)[1];
// Split the string and get the array of link based on the forward slash.
const linkArr = link.split('/')
// get the unique ID from an array.
const uniqueID = linkArr[linkArr.indexOf('d') + 1]
console.log(uniqueID);