2

I have an array of characters:

var separators = ['a', 'b', 'c'];

I want to split a string by any of the characters in this array. For instance,

var str = 'adbasscdabda';

should become

var splitUpArray = ['d', 'ss', 'd', 'd'];

How do I achieve this? I have tried splitting the string by one character at a time and then concatenating the subarrays together, but this seems unwieldy.

3 Answers 3

2

For this example you can use .match method:

var str = 'adbasscdabda';

str.match(/[^abc]+/g); // ["d", "ss", "d", "d"]

A more universal solution:

var separators = ['a', 'b', 'c'];
var re = RegExp('[^' + separators.join('') + ']+', 'g');
var str = 'adbasscdabda';

str.match(re); // ["d", "ss", "d", "d"]
Sign up to request clarification or add additional context in comments.

1 Comment

I was thinking about that. Good job.
1

You could do one loop to replace all the characters in the first array with a set character and then do a .split() using that single char. That might be simpler to maintain.

var separators = ['a', 'b', 'c']; 
var str = 'adbasscdabda'; 
for (var l = separators.length, i=0; i<l; i++) {
     str.replace(separators[i], '|');
}
var splitUpArray = str.split('|');

Comments

1

Try this.

    // Array.prototype.filter must be defined.

var splitStrByChars = function( str, chars ){
    return str.split( new RegExp( "[" + chars.join('') + "]" ) ).filter(function(a){
        return a ? a : null;
    });
};

var str = "adbasscdabda";
var separators = ['a', 'b', 'c'];

console.log( splitStrByChars( str, separators ).join( ', ' ) == "d, ss, d, d" );

2 Comments

separators.join().replace(/,/g, '') so it's [abc] rather than [a,b,c] (?)
Thanks. separators.join('') also works. ... haha. I should have used match instead of split. oh well.

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.