var str = "a[微笑]asd [听音乐] 阿达 [大笑[坏笑]sdf[坏笑] ] 今天心情不错",
reg = /\[[^\]]*|\][^\[]*|[^\[\]]+/g,
arr = str.match(reg),
res = [],
one = null,
next = null,
tagLen = 0;;

var i = 0,len = arr.length;
for(i;i<len;i++){
one = arr[i];
tagLen = 0;
if(one.indexOf("[") == 0){
tagLen = one.length - one.replace(/\[/g,"").length;
while((next = arr[++i]) && tagLen != (next.length - next.replace(/\]/g,"").length) ){
console.log("while");
}

var index = one.indexOf("[",1);
if(index != -1){
one = one.substring(0,index);
}
res.push(one);

if(next){
index = next.lastIndexOf("]");
if(index != -1){
next = next.substring(index);
}
res.push(next);
}
}else if(one.indexOf("]") != 0){
res.push(one);
}
}
console.log(res);
str = res.join("");
console.log(str);
//a[微笑]asd [听音乐] 阿达 [大笑] 今天心情不错
//这个时候的结构,就比较正常了吧,使用正则就简单了。i = 0;
str = str.replace(/\[[^\]]+\]/g,function($1,$2){
i++;
return "demo"+i;
});console.log(str);先使用一些方法,直接把错误的格式去除掉,然后格式简单了,再使用正则。应该还有更好的方法,这个方法仅供参考。