Delete Last Char of String with Javascript

前端 未结 9 703
独厮守ぢ
独厮守ぢ 2021-02-07 05:57

I have a DIV with some characters. How can I remove the last character from the text with each click on the DIV itself?

相关标签:
9条回答
  • 2021-02-07 06:11

    Edit: here's the easiest way to do this without any library dependencies

    function removeLastChar(node) {
        var i = node.childNodes.length;
        while (--i >= 0) {
            if (3 === node.childNodes[i].nodeType) {
                node.childNodes[i].data = node.childNodes[i].data.replace(/\S\s*$/, '');
                break;
            }
        }
    }
    

    /\S\s*$/ still means "the last non-space at the end"

    Note: borrowed from Tim Down's solution and further years of web development experience, :)

    0 讨论(0)
  • 2021-02-07 06:19

    Plain JavaScript:

    <div id="text">This is some text</div>
    <script>
    var node = text.firstChild;
    var nodeValue = "";
    var nodeValueLength = 0;
    text.onclick = function () {
        nodeValue = node.nodeValue;
        node.nodeValue = nodeValue.substring(0, nodeValue.length - 1);
    };
    </script>
    
    0 讨论(0)
  • 2021-02-07 06:21

    Its easy by using the attribute$= CSS3 selector which means "ends with" in your jQuery selection:

    To Delete 1st character:

    $("div[id$=/]").each(function(){ 
        this.id = this.id.substr(1);
    });
    

    To Delete Last Character:

    $("div[id$=/]").each(function(){ 
        this.id = this.id.substr(0,this.id.length - 1);
    });
    
    0 讨论(0)
提交回复
热议问题