JavaScript正则表达式修复不替换图片网址 [英] javascript regex fix for not replacing image url

查看:84
本文介绍了JavaScript正则表达式修复不替换图片网址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用正则表达式将字符串中的所有 url 替换为< a href =url> url< / a> code>。

I am using regex to replace all url in string to <a href="url">url</a>.

为此我使用

For that I am using

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标记,它将替换

it works good unless I have img tag in my string , it replaces

< img src =imgurl/> to < img src = < a href =imgurl> imgurl< / a>

我应该如何改变我的正则表达式作为一些标签属性的一部分的url?

Which change should I do to my regex to not replace urls which are part of some tag attribute ?

任何帮助都会很棒。

推荐答案

使用 Autolinker.js ,它被认为是可靠的链接。

Use Autolinker.js, it is known to be reliable with linkifying.

请参阅关于其他标签/属性内部链接的说明部分:

See the description part about links inside other tags/attributes:


将正确处理HTML输入。实用程序不会改变锚点(< a> )标记内的 href 属性(或任何其他标记/属性),并且不会意外地用新标签包装锚标签的内部文本(这会导致双重嵌套的锚标签)。

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).

以下是一个使用它的例子:

Here is an example of using it:

var linkedText = Autolinker.link(input_html, { className: "myLink" } );

这篇关于JavaScript正则表达式修复不替换图片网址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆