misteryeo misteryeo - 11 days ago 6
Javascript Question

Storing The Sliced Character from .slice Method

When I utilise the slice method like so:

"Hello".slice(0,-1);


The result I get will be "Hell". Then if I run through that again using the same code, I will get "Hel".

Is there a way that I can extract and store into a variable the actual character that was sliced off, in this case "H" or on the second run "e", and not just the remainder of the string?

Answer

You could just use a second .slice() on the original string.

For example, where "Hello".slice(0,-1); returns all but the last character, "Hello".slice(-1) returns only the last character.

var input = "Hello";
var removed = input.slice(-1);       // "o"
var remaining = input.slice(0, -1);  // "Hell"

I don't think there's a more generic solution than that, because .slice() also lets you extract the middle of a string, in which case you'd need two extra calls to get the two parts being removed.

Demo:

var input = "Hello";
var allRemoved = [];
var removed;
while (input != "") {
  allRemoved.push(removed = input.slice(-1));
  input = input.slice(0, -1);
  console.log("'" + removed + "' removed, leaving '" + input + "'");
}
console.log("Removed: " + allRemoved.join(", "));

Alternatively, if you only care about removing characters one at a time, you could forget about .slice() and instead convert the string to an array and use .shift() or .pop() to remove the character at the beginning or end respectively:

var input = "Hello";
var inArr = input.split("");
while (inArr.length > 0) {
  console.log(inArr.pop());
}