在javascript中实现类似于php.explode的函数

August 22nd, 2005 by admin Leave a reply »

在javascript中实现类似于php.explode的函数:

引用自:http://www.andrewbarker.com/home/htmDocs/@ExplodeEquivalentInJavascript


function explode(inputstring, separators, includeEmpties) {
inputstring = new String(inputstring);
separators = new String(separators);

if(separators == "undefined") {
separators = " :;";
}

fixedExplode = new Array(1);
currentElement = "";
count = 0;

for(x=0; x < inputstring.length; x++) {
char = inputstring.charAt(x);
if(separators.indexOf(char) != -1) {
if ( ( (includeEmpties <= 0) || (includeEmpties == false)) && (currentElement == "")) { }
else {
fixedExplode[count] = currentElement;
count++;
currentElement = ""; } }
else { currentElement += char; }
}

if (( ! (includeEmpties <= 0) && (includeEmpties != false)) || (currentElement != "")) {
fixedExplode[count] = currentElement; }
return fixedExplode;
}

在实际使用中,firefox和netscape都警告说“char 是保留变量”,而IE没有此提示,查了”JavaScript: The Definitive Guide, 4th Edition”,没找到相关描述,于是将变量char改为str了事。熟悉js的朋友恳请指点一下迷津

Advertisement

2 comments

  1. 炎藤 says:

    if ( ( (includeEmpties

  2. jianchina says:

    何必如此复杂,将一个字符串分割为子字符串,然后将结果作为字符串数组返回。

    stringObj.split([separator[, limit]])
    参数
    stringObj
    必选项。要被分解的 String 对象或文字。该对象不会被 split 方法修改。
    separator
    可选项。字符串或正则表达式对象,它标识了分隔字符串时使用的是一个还是多个字符。如果忽略该选项,返回包含整个字符串的单一元素数组。
    limit
    可选项。该值用来限制返回数组中的元素个数。
    说明
    split 方法的结果是一个字符串数组,在 stingObj 中每个出现 separator 的位置都要进行分解。separator 不作为任何数组元素的部分返回。

    示例
    下面的示例演示了 split 方法的用法。

    function SplitDemo(){
    var s, ss;
    var s = “The rain in Spain falls mainly in the plain.”;
    // 在每个空格字符处进行分解。
    ss = s.split(” “);
    return(ss);
    }

Leave a Reply