Starting string:
I like [dogs], [cats], and [birds]
开发者_如何学运维Final output needed:
I like <a href="#">dogs</a>, <a href="#">cats</a>, and <a href="#">birds</a>
So basically changing items with brackets to links.
Use this expression:
var str = 'I like [dogs], [cats], and [birds]';
alert(str.replace(/\[(.+?)\]/g, '<a href="#">$1</a>'));
\[(.+?)\]
asks for a literal[
, to lazily match and capture anything, then to match a literal]
. Replace with the captured stuff enclosed in<a>
tags.The
g
modifier means global replacement, i.e. find and replace every match and not just the first.
jsFiddle preview
It's a simple string replace.
function tagIt(source)
{
return source.replace('[', '<a href="#">').replace(']', '</a>');
}
精彩评论