[英]Javascript convert [url=] to html link
I'm currently trying to convert this: 我目前正在尝试将其转换为:
[url=http://example.com] this is a link [/url]
to a standard html link: 到标准的html链接:
<a href=http://example.com>this is a link</a>
So far, I can convert the url string to a link, however the [url=] [/url]
still remains and I'm not sure how to filter it out. 到目前为止,我可以将url字符串转换为链接,但是
[url=] [/url]
仍然存在,我不确定如何将其过滤掉。
message.replace(/(\b(https?):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, "<a href='$1'>$1</a>")
How can I filter out the [url=] [/url]
in the regex and also ensure this is a link
(text defined by the user) also remains? 如何过滤掉正则表达式中的
[url=] [/url]
并确保还保留this is a link
(用户定义的文本)?
You just need to add it to your replace regex: 您只需要将其添加到替换正则表达式中即可:
message.replace(/\[url=(\b(https?):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])\]/ig, "<a href='$1'>$1</a>")
^^^^^^
Though you still have the last url tag and you can make things easier with negated classes: 尽管您仍然拥有最后一个url标签,并且可以使用否定的类使事情变得更容易:
message.replace(/\[url=([^\]]+)\]\s*(.*?)\s*\[\/url\]/ig, "<a href='$1'>$2</a>")
EDIT: Made the closing tag a literal because of potential other tags 编辑:由于可能的其他标签,使结束标签成为文字
I would do that in 3 steps: 我将分三步进行:
[url=
with <a href="
[url=
替换为<a href="
[/url]
with </a>
[/url]
替换为</a>
]
with ">
">
替换]
But that's just an opinion. 但这只是一个意见。 I usually like to keep it simple, and move on to the next problem.
我通常喜欢保持简单,然后继续讨论下一个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.