最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Replace text inside of square brackets - Stack Overflow

programmeradmin3浏览0评论
var a = "[i] earned [c] coin for [b] bonus";

How to get string "__ earned __ coin for __ bonus" from the variable above in JavaScript?

All I want to do is to replace all the bracket [] and its content to __.

var a = "[i] earned [c] coin for [b] bonus";

How to get string "__ earned __ coin for __ bonus" from the variable above in JavaScript?

All I want to do is to replace all the bracket [] and its content to __.

Share Improve this question edited May 24, 2011 at 9:49 alex 490k204 gold badges889 silver badges991 bronze badges asked May 24, 2011 at 9:46 theHacktheHack 2,0149 gold badges27 silver badges34 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 11
a = a.replace(/\[.*?\]/g, '__');

if you expect newlines to be possible, you can use:

a = a.replace(/\[[^\]]*?\]/g, '__');

Here is a fun example of matching groups.

var text = "[i] italic [u] underline [b] bold";

document.body.innerHTML = text.replace(/\[([^\]]+)\]/g, '(<$1>$1</$1>)');


Breakdown

/           // BEGIN  pattern
  \[        // FIND   left bracket (literal) '['
    (       // BEGIN  capture group 1
      [     // BEGIN  character class
        ^   // MATCH  start anchor OR
        \]  // MATCH  right bracket (literal) ']'
      ]     // END    character class
      +     // REPEAT 1 or more
    )       // END    capture group 1
  \]        // MATCH  right bracket (literal) ']'
/           // END    pattern
g           // FLAG   global search
a = a.replace(/\[[^\]]+\]/g, '__');

jsFiddle.

发布评论

评论列表(0)

  1. 暂无评论