Javascript Regex: surround @_____, #_____, and http://______ with anchor tags in one pass?

做~自己de王妃 提交于 2019-12-14 01:05:39

问题


Related (but slightly different):

Surrounding all instances of @________, #___________, and http://_________ with anchor tags?

I would like to surround all instances of @_______, #________, and http://________ with anchor tags in one pass.

For example, consider this Twitter message:

The quick brown fox @Spreadthemovie jumps over the lazy dog #cow http://URL

Running it with the desired regex pattern would yield:

The quick brown fox <a href="a">@Spreadthemovie</a> jumps over the lazy
dog <a href="b">#cow</a> <a href="c">http://URL</a>

Only surround words that start with @, # or http:// so that dog@gmail.com would not become dog<b>@gmail.com</b>.


回答1:


var sample = "@sample";
sample = sample.replace(/[^\s+-+.+](@\w+|#\w+|http://[\w\./]+)[$\s+-+.+]/g, "<a>$1</a>");

$1 inserts the matched string.

Using functions (which I recommend for your particular situation):

var sample = "@sample";
sample = sample.replace(/[^\s+-+.+](@\w+|#\w+|http://[\w\./]+)[$\s+-+.+]/g, function(str) {
    var href="";
    if(str.indeoxOf("#") !== -1)
        href=str;
    else if(str.indexOf("@") !== -1)
      ...
    return "<a href="+href+">"+str+"</a>";
});

Using functions is a good idea when you want to have greater or finer control. This way is easier if you want the links to have different href's in their anchor tags.

See more here at MDC.




回答2:


s/(?<!\w)(@\w*|#\w*|http:\/\/[\w\/\.?=]*\w)/<a>$1<\/a>/g

I think this will do. It won't match @..., #... or http... if there is a number or a letter before it, which will keep e-mails away. Please test against an input set, and report any failure, so I can adequate it.

The URL, in particular, is rather tough. Right now I'm erring on the conservative side. It could be changed to stop only at dot, space and parenthesis, if you prefer.

Now, as for different links for @, # and http... you have to use a function for the replacement, as shown in the other answer.

With three passes, just do:

s/(?<!\w)(http:\/\/[\w\/\.?=]*\w)/<a href="c">$1<\/a>/g
s/(?<!\w)(#\w*)/<a href="b">$1<\/a>/g
s/(?<!\w)(@\w*)/<a href="a">$1<\/a>/g


来源:https://stackoverflow.com/questions/1181204/javascript-regex-surround-and-http-with-anchor-tags-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!