var str="Hello_Worksl_SHARED", splitStr, strMinusEnd;
strMinusEnd=(splitStr=str.split("_")).slice(0,-1);
console.log("str="+str);
console.log("splitStr="+splitStr);
console.log("strMinusEnd="+strMinusEnd);
Before your comment with extra info:
The non-removed are in your array, myFish.
splice changes the Array, that's why it returns that which has been removed.
slice, on the other hand, gives you part of the array without changing the array.
I'm not sure what you want, so here is everything:
var str="Hello_Worksl_SHARED";
var arrFromStr, arrMinusEnd, endItem;
[arrFromStr, arrMinusEnd, endItem] =
str.split("_")
.reduce(
(acc, cv, idx, arr) => {
if(idx<arr.length-1) acc[1].push(cv);
else {
acc[0]=arr;
acc[2]=cv;
};
return acc;
},
[null,[],[]]
)
;
console.log("str=\""+str+"\"");
console.log("arrFromStr=");
console.log(arrFromStr);
console.log("arrMinusEnd=");
console.log(arrMinusEnd);
console.log("endItem=\""+endItem+"\"");
.as-console-wrapper { max-height: 100% !important; top: 0; }
We're using destructuring of an array.
Right-hand-side of the = returns an array of 3 elements.
Each of those are respectfully(?) assigned to the 3 variables on the left-hand-side of that =.
The reduce is spread over multiple lines for clarity.
myFish, here.splicechanges the Array, that's why it returns that which has been removed.slice, on the other hand, gives you part of the array without changing the array.str= "Hello_Worksl_SHARED"and I'm doing split() and then splice-str.split("_").splice(-1,1)however if I need to access the non-removed array, I need to do 2 steps:let a = str.split("_")thena.splice(-1,1)and then accessa. is there a way I can do everything in 1 step?