JavaScript:链接网址,但从显示的链接文字中删除“http://”

时间:2013-11-12 11:07:04

标签: javascript regex

在JavaScript正则表达式中,如何转向,例如

Check out http://example.com/foobar#123

Check out <a href="http://example.com/foobar#123">example.com/foobar#123</a>

谢谢!

2 个答案:

答案 0 :(得分:1)

假设str是包含该文本的字符串,则只需使用capture groups

str = str.replace(/(http:\/\/)([^ ]+)/g, '<a href="$1$2">$2</a>');

这假设文本中没有已经任何链接标记,当然,因为如果存在,它会搞乱它们。只在标记文本中执行此标记的外部是非常重要的(并且只能使用单个正则表达式完全无法完成,您必须解析)。

答案 1 :(得分:1)

使用此替换呼叫:

s = 'Check out http://example.com/foobar#123';
repl = s.replace(/(https?:\/\/(\S+))/i, "<a href='$1'>$2</a>");
//=> Check out <a href='http://example.com/foobar#123'>example.com/foobar#123</a>