0

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.

user2882721
  • 221
  • 1
  • 3
  • 12

3 Answers3

1

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.

Community
  • 1
  • 1
jmt
  • 97
  • 1
  • 6
0

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

DhruvPathak
  • 42,059
  • 16
  • 116
  • 175
  • I tried your solution still i didnt get the required ouput.The output that i received is string,,,sample,a,,This, – user2882721 Feb 04 '14 at 11:09
0

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); 
Damian Krawczyk
  • 2,241
  • 1
  • 18
  • 26