我有一个像这样的字符串:
var str = "this is [link1][1]
this is [link2][2]
this is [link3][3]
this is [link4][4]
[1]: http://example1.com
[2]: http://example2.com
[3]: http://example1.com
[4]: http://example4.com";
现在我想要这个:
var str = "this is [link1][1]
this is [link2][2]
this is [link3][1]
this is [link4][4]
[1]: http://example1.com
[2]: http://example2.com
[4]: http://example4.com";
正如您在上面的示例中看到的,有两件事:
- 删除所有这些网址之间的冗余
\n
(仅网址) - 删除重复的URL并替换refrence-number。(换句话说,在上面的示例中,因为第一个和第三个URL相同,所以
[3]: http://example1.com
已删除并用[1]
替换[3]
)
有一个正则表达式匹配 [任意数字]:
及其 url
分为两组:
/(\[[0-9]*]:)\s*(.*)\r?\n?/gm
在 str
中,该正则表达式匹配:
//group1
$1: [1]:
[2]:
[3]:
[4]:
//group2
$2: http://example1.com
http://example2.com
http://example1.com
http://example4.com
<小时/>
还有另一个正则表达式可以删除仅链接之间的所有浪费\n
:
str.replace(/(^\[[0-9]*]:.*)\n+/gm, $1\n);
<小时/>
那么,我该怎么做呢?
最佳答案
这可能是您问题的解决方案:
function removeMultipleMatkdownLinks(markownString) {
var seperateLinks = /(\[[0-9]*]):\s*(.*)\r?\n?/gm;
var removeNewLines = /(^\[[0-9]*]:.*)\n+/gm;
var result;
var urls = [], ids = [];
var formattedString = str;
while ((result = seperateLinks.exec(str)) !== null) {
if (result.index === seperateLinks.lastIndex) {
result.lastIndex++;
}
//check if link already exists
var index = urls.indexOf(result[2]);
if(index < 0) {
urls.push(result[2]);
ids.push(result[1]);
} else { //remove links and replace ids
var removeLink = new RegExp("(\\" + result[1] + ":.*\\r?\\n?)", "gm"); ///(\[1\]:.*\n)/gm
var changeNumber = new RegExp("(\\" + result[1] + ")", "gm");
formattedString = formattedString
.replace(removeLink, "")
.replace(changeNumber, ids[index]);
}
}
return formattedString.replace(removeNewLines, "$1\n");
}
关于javascript - 如何为字符串中所有相同的 URL 定义相同的数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34947640/