我有一個帶有如下鏈接的降價文本檔案:
[Text](https://docs.google.com/document/d/unique-doc-id-here/edit)
or
[Text2](https://docs.google.com/document/d/unique-doc-id-here")
我想href
用另一個替換整個unique-doc-id-here
,把它傳遞給一個回傳新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)
uj5u.com熱心網友回復:
您可以使模式更具體,然后使用組 1 值。
(\[[^\][]*]\()https?:\/\/docs\.google\.com\/document\/d\/([^\s\\\/)] )[^\s)]*\)
部分中的模式匹配:
(\[[^\][]*]\()
捕獲組 1,[...](
使用否定字符類進行匹配https?:\/\/docs\.google\.com\/document\/d\/
匹配url的前導部分(
捕獲組 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);
uj5u.com熱心網友回復:
您可以href
通過使用從字串中獲取鏈接RegEx
,然后使用正斜杠將其拆分來實作此目的。
試試這個(在下面的代碼片段中添加了描述性注釋):
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);
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/517302.html