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

3

28

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 ?

Uncrown answered 14/5, 2013 at 9:55 Comment(3)
Why don't you just put input value into div?Dithionite
Just trying to learn everything. :)Uncrown
Great question - I found many many answers for how to trim characters from a string. You worded your question well to help me find it with searching. Thanks!Hanover
N
61
$('#mainn').text(function (_,txt) {
    return txt.slice(0, -1);
});

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

Nicolas answered 14/5, 2013 at 9:56 Comment(3)
Don't call text() twice, unnecessarily: $('#mainn').text(function (i, t) {return t.slice(-1); });Maineetloire
I have figured out the issue. The BACKSPACE keycode does not register when executed from within the text box for some reason. The code you suggested works perfectly, its just that my preceding code is non-functional. Thanks :DUncrown
.slice(-1) will return just the last character. The question was to remove the last character...Amphimacer
A
7

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());
Aleenaleetha answered 14/5, 2013 at 10:9 Comment(1)
I have considered that as an option, but never even thought about backspacing from the middle! Thanks for the suggestion :DUncrown
I
3
var string = "Hello";
var str = string.substring(0, string.length-1);
alert(str);

http://jsfiddle.net/d72ML/

Involucrum answered 14/5, 2013 at 9:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.