Javascript正则表达式:环绕@_____,#_____,和http:// ______,一次性使用锚标签? [英] Javascript Regex: surround @_____, #_____, and http://______ with anchor tags in one pass?
问题描述
我想包围所有 @_______
的实例, #________
和 http:// ________
一次性使用锚标签。
I would like to surround all instances of @_______
, #________
, and http://________
with anchor tags in one pass.
例如,考虑一下这条Twitter消息:
For example, consider this Twitter message:
快速的棕色狐狸@ Spreadthemovie跳过懒狗#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>
仅包围以 @
开头的单词, #
或 http://
以便 dog@gmail.com
不会成为 dog< b> @ gmail.com< / b>
。
Only surround words that start with @
, #
or http://
so that dog@gmail.com
would not become dog<b>@gmail.com</b>
.
推荐答案
var sample = "@sample";
sample = sample.replace(/[^\s+-+.+](@\w+|#\w+|http://[\w\./]+)[$\s+-+.+]/g, "<a>$1</a>");
$ 1
插入匹配的字符串。
使用函数(我推荐用于您的特定情况):
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>";
});
当你想拥有更强或更好的控制时,使用函数是一个好主意。如果您希望链接在其锚标记中具有不同的href,则这种方式更容易。
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.
查看更多这里是MDC 。
这篇关于Javascript正则表达式:环绕@_____,#_____,和http:// ______,一次性使用锚标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!