Martín
Martín

Reputation: 3125

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?

Upvotes: 6

Views: 223

Answers (3)

Tim Pietzcker
Tim Pietzcker

Reputation: 336128

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?"

Upvotes: 3

Ole
Ole

Reputation: 406

As first approximation to a possible solution could be:

".*[^=]=[^=].*"

Note that this is just the regex, if you want to use it with egrep, sed, java regex or whatever, take care if something needs to be escaped.

BEWARE!: This is a first approximation, this could be improved. Note that, for instance, this regex won't match this string "=" (null - equal - null).

Upvotes: -1

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382122

You can use a regex :

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

\b checks for word boundaries.

Upvotes: 6

Related Questions