Reputation: 13
I'm programming a simple calculator with javascript, and I'm finding it hard to make a correct backspace function.
When the backspace button is clicked, I want it to remove the last character on the screen.
NB: I know I'm nowhere close to the correct solution, I'm a newbie, so go easy on me :D.
Here's my code:
// Clear and backspace
function clearAll() {
if (control){
lastScreen = screenView.value;
screenView.value = 0;
alert("cleared!");
}
}
function backSpace() {
if (control) {
var newScreenView = [];
if (screenView.value != 0) {
screenViewLength = screenView.value.length;
for (i = 0; i < screenViewLength; i++) {
newScreenView.push(screenView.value[i]);
}
remove = newScreenView.length ;
console.log(newScreenView[remove]);
//screenView.value = newScreenView;
}
alert("backspace");
}
}
<input type="button" id="backspace_button" onclick="backSpace()" value="<="/>
Upvotes: 1
Views: 6244
Reputation: 4053
Simply use substr
method:
screenView.value = screenView.value.substr(0, screenView.value.length - 1)
But if you hold the user input in a buffer
:
buffer.pop()
screenView.value = buffer.join('')
Upvotes: 0
Reputation: 1350
function backSpace(){
screenView.value = screenView.value.slice(0, - 1);
}
One liner right there!
Upvotes: 0
Reputation: 711
Just slice the string
screenView.value = screenView.value.slice(0, screenView.value.length -1)
Upvotes: 4