简体   繁体   中英

splitting a string based on delimiter using javascript

Hi I'm trying to split a string based on multiple delimiters.Below is the code

var data="- This, a sample string.";
var delimiters=[" ",".","-",","];
var myArray = new Array();

for(var i=0;i<delimiters.length;i++)
{
if(myArray == ''){
    myArray = data.split(delimiters[i])
}
else
{
    for(var j=0;j<myArray.length;j++){
        var tempArray = myArray[j].split(delimiters[i]);
        if(tempArray.length != 1){
            myArray.splice(j,1);
            var myArray = myArray.concat(tempArray);
        }

    }
}
}
console.log("info","String split using delimiters is  - "+ myArray); 

Below is the output that i get

a,sample,string,,,,This,

The output that i should get is

This
a
sample
string

I'm stuck here dont know where i am going wrong.Any help will be much appreciated.

You could pass a regexp into data.split() as described here .

I'm not great with regexp but in this case something like this would work:

var tempArr = [];
myArray = data.split(/,|-| |\./);
for (var i = 0; i < myArray.length; i++) {
    if (myArray[i] !== "") {
        tempArr.push(myArray[i]);
    }
}
myArray = tempArr;
console.log(myArray);

I'm sure there's probably a way to discard empty strings from the array in the regexp without needing a loop but I don't know it - hopefully a helpful start though.

Check for string length > 0 before doing a concat , and not != 1 . Zero length strings are getting appended to your array.

Here you go:

    var data = ["- This, a sample string."];
    var delimiters=[" ",".","-",","];
    for (var i=0; i < delimiters.length; i++) {
        var tmpArr = [];
        for (var j = 0; j < data.length; j++) {
            var parts = data[j].split(delimiters[i]);
            for (var k = 0; k < parts.length; k++) {
                if (parts[k]) {
                    tmpArr.push(parts[k]);
                }
            };
        }
        data = tmpArr;
   }
   console.log("info","String split using delimiters is  - ", data); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM