【发布时间】:2013-01-30 07:56:08
【问题描述】:
我需要带有以下格式链接的解析文本:
[html title](http://www.htmlpage.com)
http://www.htmlpage.com
http://i.imgur.com/OgQ9Uaf.jpg
这两个字符串的输出是:
<a href='http://www.htmlpage.com'>html title</a>
<a href='http://www.htmlpage.com'>http://www.htmlpage.com</a>
<a href='http://i.imgur.com/OgQ9Uaf.jpg'>http://i.imgur.com/OgQ9Uaf.jpg</a>
字符串可以包含任意数量的这些链接,即:
[html title](http://www.htmlpage.com)[html title](http://www.htmlpage.com)
[html title](http://www.htmlpage.com) [html title](http://www.htmlpage.com)
[html title](http://www.htmlpage.com) wejwelfj http://www.htmlpage.com
输出:
<a href='http://www.htmlpage.com'>html title</a><a href='http://www.htmlpage.com'>html title</a>
<a href='http://www.htmlpage.com'>html title</a> <a href='http://www.htmlpage.com'>html title</a>
<a href='http://www.htmlpage.com'>html title</a> wejwelfj <a href='http://www.htmlpage.com'>http://www.htmlpage.com</a>
我有一个非常长的函数,它通过传递字符串 3 次来完成工作,但我无法成功解析这个字符串:
[This](http://i.imgur.com/iIlhrEu.jpg) one got me crying first, then once the floodgates were opened [this](http://i.imgur.com/IwSNFVD.jpg) one did it again and [this](http://i.imgur.com/hxIwPKJ.jpg). Ugh, feels. Gotta go hug someone/something.
为简洁起见,我将发布我尝试过的正则表达式,而不是整个查找/替换函数:
var matchArray2 = inString.match(/\[.*\]\(.*\)/g);
对于匹配[*](*),不起作用,因为[]()[]() 已匹配
真的是这样,我猜。一旦我进行了匹配,我就会搜索匹配的 () 和 [] 以解析出链接和链接文本并构建 href 标记。我从临时字符串中删除了匹配项,因此当我第二次查找普通超链接时我不匹配它们:
var plainLinkArray = tempString2.match(/http\S*:\/\/\S*/g);
我没有用正则表达式解析任何 html。我正在解析一个字符串并尝试输出 html。
编辑:我添加了它在事后解析第三个链接http://i.imgur.com/OgQ9Uaf.jpg 的要求。
我的最终解决方案(基于@Cerbrus 的回答):
function parseAndHandleHyperlinks(inString)
{
var result = inString.replace(/\[(.+?)\]\((https?:\/\/.+?)\)/g, '<a href="$2">$1</a>');
return result.replace(/(?: |^)(https?\:\/\/[a-zA-Z0-9/.(]+)/g, ' <a href="$1">$1</a>');
}
【问题讨论】:
-
What have you tried?正如这里的许多人会告诉你的那样,用正则表达式解析 HTML ......那样疯狂,@ 987654323@ 当然,如果你必须处理它的唯一标记是可能的,但请研究替代方案
-
我想不出that会有用的地方...
-
@jahroy:您看到这里的网址是如何制作的吗?让我给你一个提示:
[title](url)或[title][1] <....> [1]:url。像这样的解析器在论坛和其他类似的社区网站上很有用。 -
另外,@EliasVanOotegem:尝试解释 HTML 文档和尝试将一种特定格式解析为 HTML 是有区别的。
-
@cerbrus:你说得对,我只是说 regex、html 和 parse,所以我跳到错误的结论。但是,当我发表评论时,没有任何代码可以显示 OP 迄今为止尝试过的内容,所以我将评论保留原样
标签: javascript regex