我正在使用正则表达式来替换所有 url
字符串为<a href="url">url</a>
.
为此我正在使用
if(!String.linkify) {
String.prototype.linkify = function() {
// http://, https://, ftp://
var urlPattern = /\b(?:https?|ftp):\/\/[a-z0-9-+&@#\/%?=~_|!:,.;]*[a-z0-9-+&@#\/%=~_|]/gim;
// www. sans http:// or https://
var pseudoUrlPattern = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
// Email addresses
var emailAddressPattern = /[\w.]+@[a-zA-Z_-]+?(?:\.[a-zA-Z]{2,6})+/gim;
return this
.replace(urlPattern, '<a href="$&">$&</a>')
.replace(pseudoUrlPattern, '$1<a href="http://$2">$2</a>')
.replace(emailAddressPattern, '<a href="mailto:$&">$&</a>');
};
}
和
mystr.linkify();
来自这里,https://stackoverflow.com/a/7123542/1602333
它工作得很好,除非我的字符串中有 img 标签,它会替换
<img src="imgurl"/>
至<img src="<a href="imgurl">imgurl</a>"
我应该对正则表达式进行哪些更改才能不替换属于某些标签属性一部分的网址?
任何帮助都会很棒。
最佳答案
使用 Autolinker.js
,已知它对于链接是可靠的。
请参阅有关其他标签/属性内的链接的描述部分:
Will properly handle HTML input. The utility will not change the
href
attribute inside anchor (<a>
) tags (or any other tag/attribute for that matter), and will not accidentally wrap the inner text of an anchor tag with a new one (which would cause doubly-nested anchor tags).
这是一个使用它的示例:
var linkedText = Autolinker.link(input_html, { className: "myLink" } );
关于javascript 正则表达式修复不替换图像 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32584155/