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.

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

this will also produce empty items in output array
So it did because of the splice, edited it now and it produces the required result
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); 

Comments

0

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

1 Comment

I tried your solution still i didnt get the required ouput.The output that i received is string,,,sample,a,,This,

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.