Javascript:如何从div或字符串中删除最后一个字符?

时间:2023-02-11 00:02:17

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?

我有一个div,里面有一串内容。内容没有存储在变量中,我想删除这个div中文本的最后一个字符。有什么帮助吗?

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:

我有一个文本字段,在文本字段中输入文本时,文本会以大号字体出现在div中。当用户点击backspace键时,我希望删除div中的最后一个字符。我主要使用jQuery来实现这一点。这是我的代码:

$(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);

我有尝试$(' # 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 ?

我也尝试过将#theInput的值存储在一个变量中,然后打印出来,但没有成功。什么好主意吗?

3 个解决方案

#1


58  

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

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

演示- - > http://jsfiddle.net/d72ML/8/

#2


6  

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。在按键弹起

$("#div").html($("#input").val());

#3


3  

var string = "Hello";
var str = string.substring(0, string.length-1);
alert(str);

http://jsfiddle.net/d72ML/

http://jsfiddle.net/d72ML/

#1


58  

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

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

演示- - > http://jsfiddle.net/d72ML/8/

#2


6  

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。在按键弹起

$("#div").html($("#input").val());

#3


3  

var string = "Hello";
var str = string.substring(0, string.length-1);
alert(str);

http://jsfiddle.net/d72ML/

http://jsfiddle.net/d72ML/