Delete Last Char of String with Javascript

前端 未结 9 733
独厮守ぢ
独厮守ぢ 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:06

    Alternative to Jonathan's answer, how to delete the first character:

    $("div.myDiv").click(function(){
        $(this).html($(this).text().substring(1));
    });
    

    Or, remove the last character:

    $("div.myDiv").click(function(){
        $(this).html($(this).text().replace(/.$/g, ''));
    });
    

    Or, go crazy and remove a character from a random place:

    $("div.myDiv").click(function(){
        var text = $(this).text();
        var index = Math.round(Math.random() * (text.length - 1));
        var result = text.substring(0, index) + text.substring(index + 1, text.length - 1);
        $(this).html(result);
    });
    

    Instead of random place, you can use the above function with a predefined index to remove from a specific location.

提交回复
热议问题