我正在尝试使用这个函数从value
中创建2个结果。
function split(val){
return val.split( /,\s*/ );
};
value = "Jim, ";
var terms = split( value );
terms;
所有其他浏览器(包括IE9)将产生terms = ["Jim", ""]
然而,IE8和可能是IE7会产生这个结果:terms = ["Jim"]
有没有人有任何建议或替代方案可以在IE8上起作用?
我正在尝试使用这个函数从value
中创建2个结果。
function split(val){
return val.split( /,\s*/ );
};
value = "Jim, ";
var terms = split( value );
terms;
所有其他浏览器(包括IE9)将产生terms = ["Jim", ""]
然而,IE8和可能是IE7会产生这个结果:terms = ["Jim"]
有没有人有任何建议或替代方案可以在IE8上起作用?
您可能最好选择以下方案:
val.split(',')
这似乎在所有浏览器中都能始终如一地工作。
在逗号后面的任何尾随空格仍然必须在之后剥离。可以按照以下方式进行处理:
for (var i = 0; i < terms.length; i++) {
terms[i] = terms[i].replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}
split()
忽略。但使用字符串参数则能正常工作:'axx'.split('x') // All browsers: ["a", "", ""]
'axx'.split(/x/) // IE6/7/8: ["a"], all other browsers: ["a", "", ""]
你需要重写正则表达式。
试试这个。
String.prototype.trim = String.prototype.trim || function() {
return this.replace(/^\s+|\s+$/g, '');
}
function split( str ){
return (""+str).trim().split( /\,/ );
}
", "
) 进行分割时,IE8 的行为是正确的,但在使用正则表达式进行分割时却没有最后的空字符串...很奇怪。 - Niet the Dark Absol