开发者

How do I replace multiple items in a string?

开发者 https://www.devze.com 2023-02-09 21:16 出处:网络
Starting string: I like [dogs], [cats], and [birds] 开发者_如何学运维Final output needed: I like <a href=\"#\">dogs</a>, <a href=\"#\">cats</a>, and <a href=\"#\">bi

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>');
}
0

精彩评论

暂无评论...
验证码 换一张
取 消