6
启动串:如何替换字符串中的多个项目?
I like [dogs], [cats], and [birds]
最终输出的需要:
I like <a href="#">dogs</a>, <a href="#">cats</a>, and <a href="#">birds</a>
所以基本上改变项目和括号来链接。
启动串:如何替换字符串中的多个项目?
I like [dogs], [cats], and [birds]
最终输出的需要:
I like <a href="#">dogs</a>, <a href="#">cats</a>, and <a href="#">birds</a>
所以基本上改变项目和括号来链接。
使用该表达式:
var str = 'I like [dogs], [cats], and [birds]';
alert(str.replace(/\[(.+?)\]/g, '<a href="#">$1</a>'));
\[(.+?)\]
询问文字[
,懒洋洋地匹配和捕获任何东西,然后匹配一个]
。替换为附在<a>
标签中的捕获内容。
g
修饰符意味着全局替换,即查找并替换每个匹配,而不仅仅是第一个。
这是一个简单的字符串替换。
function tagIt(source)
{
return source.replace('[', '<a href="#">').replace(']', '</a>');
}
@Trufa:我会说,远非如此。 – BoltClock 2011-02-08 18:35:42