Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: How to remove the last character from a div or a string?

I have a div with a string of content in it. The content is not stored in a variable and I would like to remove the last character of the text in this div. Any help please?

More info:


I have a text field, and upon entering text into the text field, the text appears in a div in large writing. When the user hits the back-space key, I want the last character in the div to be deleted. I am mainly using jQuery to achieve this. Here is my code:

$(document).ready(function(){     $("#theInput").focus();   //theInput is the text field      $('#theInput').on('keypress', printKeyPress);      function printKeyPress(event)     {         //#mainn is the div to  hold the text         $('#mainn').append(String.fromCharCode(event.keyCode));         if(event.keyCode ==8)   //if backspace key, do below         {             $('#mainn').empty();  //my issue is located here...I think         }     }  }); 

I have attempted $('#mainn').text.slice(0,-1);

I have also tried storing the value of #theInput in a variable and then printing it, but that didn't work. Any ideas ?

like image 302
xa. Avatar asked May 14 '13 09:05

xa.


People also ask

How do you delete the last character in a string JavaScript?

To remove the last character from a string in JavaScript, you should use the slice() method. It takes two arguments: the start index and the end index. slice() supports negative indexing, which means that slice(0, -1) is equivalent to slice(0, str. length - 1) .

How do you exclude the last character of a string?

Using String. The easiest way is to use the built-in substring() method of the String class. In order to remove the last character of a given String, we have to use two parameters: 0 as the starting index, and the index of the penultimate character.

How do I remove the last 3 characters from a string?

slice() method to remove the last 3 characters from a string, e.g. const withoutLast3 = str. slice(0, -3); . The slice method will return a new string that doesn't contain the last 3 characters of the original string.


2 Answers

$('#mainn').text(function (_,txt) {     return txt.slice(0, -1); }); 

demo --> http://jsfiddle.net/d72ML/8/

like image 178
Mohammad Adil Avatar answered Sep 20 '22 01:09

Mohammad Adil


Are u sure u want to remove only last character. What if the user press backspace from the middle of the word.. Its better to get the value from the field and replace the divs html. On keyup

$("#div").html($("#input").val()); 
like image 20
lintu Avatar answered Sep 19 '22 01:09

lintu