Is there any trouble splitting variables that were previously split and overwrite the original variable while doing so?
Example:
arr = str.split(" ");
arr = arr[0].split("/");
I tested it and it works. But:
- Is it risky to do this?
- Will it behave as I expect at all times, and on all browsers?
That will be fine in all browsers. There’s no risk.
You are simply assigning the variable
arrto refer to something new, it doesn’t matter what it used to refer to. (This doesn’t actually “overwrite the older array”, but if there are no other references to the old array the garbage collector will take care of it.)You can also do it in one line:
Note that according to MDN,
.split()always returns an array with at least one element, even if the source string was empty or didn’t contain the separator.EDIT: If both source string and separator are empty strings
.split()seems to return an empty array. I.e.,"".split("")returns[]. Thanks Munim for pointing that out. (But"".split(" ")returns[""]so there will be no problem for purposes of this question.)