Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split by a character in JavaScript but not contiguous ones

Here is the case:

var stringExample = "hello=goodbye==hello";
var parts = stringExample.split("=");

Output:

hello,goodbye,,hello

I need this Output:

hello,goodbye==hello

Contiguous / repeated characters must be ignored, just take the single "=" to split.

Maybe some regex?

like image 252
Martín Avatar asked Jan 08 '13 14:01

Martín


2 Answers

You can use a regex :

var parts = stringExample.split(/\b=\b/);

\b checks for word boundaries.

like image 120
Denys Séguret Avatar answered Oct 26 '22 20:10

Denys Séguret


Most probably, @dystroys answer is the one you're looking for. But if any characters other than alphanumerics (A-Z, a-z, 0-9 or _) could surround a "splitting ="), then his solution won't work. For example, the string

It's=risqué=to=use =Unicode!=See?

would be split into

"It's", "risqué=to", "use Unicode!=See?"

So if you need to avoid that, you would normally use a lookbehind assertion:

result = subject.split(/(?<!=)=(?!=)/);  // but that doesn't work in JavaScript!

So even though this would only split on single =s, you can't use it because JavaScript doesn't support the (?<!...) lookbehind assertion.

Fortunately, you can always transform a split() operation into a global match() operation by matching everything that's allowed between delimiters:

result = subject.match(/(?:={2,}|[^=])*/g);

will give you

"It's", "risqué", "to", "use ", "Unicode!", "See?"
like image 41
Tim Pietzcker Avatar answered Oct 26 '22 20:10

Tim Pietzcker