String.split() bug??
-
Is this a bug or am I missing something ?
const leString = "ABC 12345 67"; // note the double space Console.print(leString.split(" ")[0]); // prints "ABC" correctly Console.print(leString.split(" ")[1]); // prints nothing
-
@aaronventure Looks like an issue with multiple spaces. Not sure if it's a bug or a 'trimming' feature?
This works, of course (1 space):
const leString = "ABC 12345 67"; Console.print(leString.split(" ")[0]); // prints "ABC" correctly Console.print(leString.split(" ")[1]); // prints "12345" correctly
but weirdly so does this:
const leString = "ABC 12345 67"; Console.print(leString.split(" ")[0]); // prints "ABC" correctly Console.print(leString.split(" ")[1]); // prints "12345" correctly
So it looks like the spaces in the split function are collapsed to one space, which means they won't find the double space the string.
-
@aaronventure Actually, when splitting by any amount of multiple characters it only seems to use the first character:
const leString = "ABC 12345 67"; Console.print(leString.split("234")[0]); // prints "ABC 1" correctly Console.print(leString.split("234")[1]); // prints "345 67" incorrectly
I would expect the second print to be "5 67", like in the browser console:
> "ABC 12345 67".split("234")[0] < "ABC 1" > "ABC 12345 67".split("234")[1] < "5 67"
-
@dannytaurus Confirmed, it only uses the first char, so the rest is untouched
@aaronventure in your first example, if you print the third element you get the numbersSo in short, you can't use a chain of char to split, only a unique char
-
Checked the source and the highlighted line in the
split
function substrings only the first character of the separator so it seems intentional.// HISE/hi_scripting/scripting/engine/JavascriptEngineObjects.cpp static var split(Args a) { const String str(a.thisObject.toString()); const String sep(getString(a, 0)); StringArray strings; if (sep.isNotEmpty()) strings.addTokens(str, sep.substring(0, 1), ""); // 👈 THIS LINE else // special-case for empty separator: split all chars separately for (String::CharPointerType pos = str.getCharPointer(); !pos.isEmpty(); ++pos) strings.add(String::charToString(*pos)); var array; for (int i = 0; i < strings.size(); ++i) array.append(strings[i]); return array; }