Character separation in JavaScript, but not contiguous

Like this:

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

Conclusion:

 hello,goodbye,,hello 

I need this output:

 hello,goodbye==hello 

Adjacent / duplicate characters should be ignored, just select a single "=" to separate.

Maybe some kind of regular expression?

+6
source share
3 answers

You can use regex:

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

\b checks for word boundaries.

+6
source

Most likely the @dystroys answer is the one you are looking for. But if any characters other than alphanumeric characters ( AZ , AZ , 0-9 or _ ) can surround "splitting = "), then its solution will not work. For example, the line

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

will be broken down into

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

So, if you need to avoid this, you will usually use the lookbehind statement:

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

So, although this will only be split into one = s, you won’t be able to use it because JavaScript does not support the statement (?<!...) lookbehind.

Fortunately, you can always convert a split() operation to a global match() operation, matching everything that is allowed between the delimiters:

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

will provide you

 "It's", "risqué", "to", "use ", "Unicode!", "See?" 
+3
source

As a first approximation to a possible solution, there could be:

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

Please note that this is just a regular expression, if you want to use it with egrep, sed, java regex or any other, take care if something needs to be escaped.

BEWARE !: This is the first approximation, it could be improved. Note that, for example, this regular expression will not match this string "=" (null - equal - null).

-1
source

All Articles