John Verber
John Verber

Reputation: 755

String split with multiple separators

I'm trying to split a huge string that uses "}, {" as it's separator.

If I use the following code will I get split it into it's own string?

var i;
var arr[];
while(str) {
    arr[i] = str.split("/^}\,\s\{\/");
}

Upvotes: 1

Views: 5670

Answers (3)

Jeremy J Starcher
Jeremy J Starcher

Reputation: 23863

var s = 'Hello"}, {"World"}, {"From"}, {"Ohio';
var a = s.split('"}, {"');
alert(a);

Upvotes: 0

I Hate Lazy
I Hate Lazy

Reputation: 48789

First, get rid of the while loop. Strings are immutable, so it won't change, so you'll have an infinite loop.

Then, you need to get rid of the quotation marks to use regex literal syntax and get rid of the ^ since that anchors the regex to the start of the string.

/},\s\{/

Or just don't use a regex at all if you can rely on that exact sequence of characters. Use a string delimiter instead.

"}, {"

Also, this is invalid syntax.

var arr[];

So you just do the split once, and you'll end up with an Array of strings.

All in all, you want something like this.

var arr = str.split(/*your split expression*/)

Upvotes: 6

ilan berci
ilan berci

Reputation: 3881


var arr = str.split(/[\{\},\s]+/)

Upvotes: 0

Related Questions