导航栏: 首页 评论列表

悲催的String.split(RegExp)有兼容性问题

默认分类 2012-12-20 12:01:12

String.split()

需求描述:
需要将一个字符串需要根据正则表达式分割成多段

代码实现(使用正则):

var tplStr,
    sep,
    r,
    sepStr,
    i;

sep = /<!--\s*target:\s*([a-zA-Z0-9]+)\s*-->/g;
tplStr = '<!--target:aaa-->a<\!--target:bbb-->b';

r = tplStr.split(sep);
//IE: r = ['a','b'];
//FF: r = ['','aaa','a','bbb','b'];
//GC: r = ['','aaa','a','bbb','b'];

解决方案:
使用一个不重复的字符串做分隔符进行分割

var tplStr,
    sep,
    r,
    sepStr,
    i;

sep = /<!--\s*target:\s*([a-zA-Z0-9]+)\s*-->/g;
tplStr = '<!--target:aaa-->a<\!--target:bbb-->b';

r = tplStr.split(sep);
//IE: r = ['a','b'];
//FF: r = ['','aaa','a','bbb','b'];
//GC: r = ['','aaa','a','bbb','b'];

//找到一个不重复的字符串做分隔符
sepStr = String(Math.random()).replace('.','');
for( i=0; tplStr.indexOf(sep)>-1 && i<1000; i++){sep = String(Math.random()).replace('.','');}
if (tplStr.indexOf(sep)>-1) { throw { title: 'BUI Template Error: ',name: 'Math.random()'} }

r = tplStr.replace(sep,sepStr).split(sepStr);
//IE: r = ['','a','b'];
//FF: r = ['','a','b'];
//GC: r = ['','a','b'];


>> 留言评论