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?
You can use a regex :
var parts = stringExample.split(/\b=\b/);
\b
checks for word boundaries.
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?"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With