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);先使用一些方法,直接把错误的格式去除掉,然后格式简单了,再使用正则。应该还有更好的方法,这个方法仅供参考。
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);先使用一些方法,直接把错误的格式去除掉,然后格式简单了,再使用正则。应该还有更好的方法,这个方法仅供参考。
解决方案 »
- 刚接触js。JS文件在IE中能显示,但在火狐中显示不出来,跪求高手指出...
- js实现一种加密算法问题
- Ext TreePanel 获取节点值的问题???
- javascript ff和ie的事件onclick两种方法中出现的疑问
- jQuery jBox的一个小问题 请达人帮助解决下 我折腾好长时间没弄明白了
- 请教如何截取小数点前面的字符串,如单批danpiianj2.doc截取成danpiianj2?
- ie window.open 问题!!谢谢!!!
- 我想要一段代码,是服务器上的网页,调用本地机上的应用程序,在线等!!
- 关于document.execCommand()函数的问题(急)
- 怎么实现http://sms.sina.com.cn/cgi-bin/sms/ringlist.cgi?aid=31&type=&sort=2里那些下拉菜单呢。
- 图片地址想改成绝对引用的,但是改不成功
- Javascript执行上下文和eval的困惑
代码嘛,总归是有些规律的,才能实现,当出现了不规律的,直接当错误处理掉算了。所以,sorry了。