简体   繁体   中英

Remove the last letter of the string using click - javascript

Sorry about this noob question, I am trying to create a button that would remove the last letter of the string just by clicking it using a EventListener. As of now it does not work. Button 1 and 2 are working fine. The Clear button is working as well. It's just the cancel button that is not working. I am trying to use the slice method. I am not really sure how to do this and why its not working. Please see the code below for reference. Thanks in advanced for the help guys.

 //PLACE HOLDER FOR THE RESULT let Result = document.getElementById("result"); Result.innerText = "RESULT HERE"; // CLEAR BUTTON let clear = document.querySelector('.clear-tasks'); // EVENT LISTENER TO CLEAR THE BUTTON clear.addEventListener('click', function(e) { Result.textContent = 0; }); //ONE BUTTON const numberOne = document.querySelector('.one'); // EVENT LISTENER TO CONCATINATE 1 numberOne.addEventListener('click', runEventOne); function runEventOne(e) { if (Result.textContent === 'RESULT HERE' || Result.textContent === '0') { Result.textContent = 1; } else { Result.textContent += 1; } } // TWO const numberTwo = document.querySelector(".two"); // EVENT LISTENER TO CONCATINATE 2 numberTwo.addEventListener('click', runEventTwo); function runEventTwo(e) { if (Result.textContent === 'RESULT HERE' || Result.textContent === '0') { Result.textContent = 2; } else { Result.textContent += 2; } } // CANCEL const cancel = document.querySelector(".cancel"); cancel.addEventListener('click', function(e) { Result.textContent.slice(0, -1); }); 
 body { margin: 0px auto; width: 600px; } p { font-size: 23px; float: left; padding: 30px; border: solid #336336 2px; margin: 20px; } 
 <h1 id="result"></h1> <p id="1" class="one">1</p> <p id="2" class="two">2</p> <br><br> <p class="cancel">cancel</p> <p class="clear-tasks"> CLEAR</p> 

The code is actually correct, the only thing is that you need to set the result of the slice method to the Result textContent again.

  // CANCEL
const cancel = document.querySelector(".cancel");
    cancel.addEventListener('click',function(e){
    Result.textContent = Result.textContent.slice(0, -1);
});

And voila!

PS: Posting an answer and not a comment because I have not enough reputation to do so.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice

The slice() method extracts a section of a string and returns it as a new string.

The original string is not changed. Like the others have said...

Result.textContent = Result.textContent.slice(0, -1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM