使用Javascript删除字符串的最后一个字符

时间:2010-01-02 01:23:28

标签: javascript jquery string

我有DIV个字符。如何在每次点击DIV本身时删除文本中的最后一个字符?

9 个答案:

答案 0 :(得分:26)

删除第一个字符

​$("div").on("click", function(){
    $(this).text(function(index, text){
        return text.replace(/^.(\s+)?/, '');
    });
});​​​​​​​​​​​​

删除最后一个字符

$("div").on("click", function(){
    $(this).text(function(index, text){
        return text.replace(/(\s+)?.$/, '');
    });
});

删除特定字符

$("div").on("click", function(){
    $(this).text(function(index, text){
        return text.replace(/r/gi, '');
    });
});

在以下位置查看每个在线示例:http://jsfiddle.net/Xcn6s/

答案 1 :(得分:23)

假设你有一个div的引用,它只包含一个文本节点(正如你的问题所暗示的那样),这很简单。这是一个非jQuery解决方案:

div.onclick = function() {
    var textNode = this.firstChild;
    textNode.data = textNode.data.slice(0, -1);
};

答案 2 :(得分:2)

替代Jonathan的回答,如何删除第一个字符:

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

或者,删除最后一个字符:

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

或者,发疯并从随机位置移除角色:

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

您可以使用具有预定义索引的上述函数从特定位置删除,而不是随机位置。

答案 3 :(得分:2)

每次单击div时都会删除一个字符。没有更多要求,我不能再给你了。

<html>

<head>
    <script>

    function deleteChar(div) {
       div.innerHTML = div.innerHTML.replace(/.$/, '');
    }

    </script>
</head>

<body>

    <div onclick="deleteChar(this)">this is my div</div>

</body>
</html>

哦,对不起,你问jquery ......好吧,这是你用直接javascript做的。

答案 4 :(得分:2)

编辑:这是最简单的方法,没有任何库依赖

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*$/ 表示“最后的最后一个非空格”

注意:借鉴Tim Down的解决方案和更多年的网络开发经验,:)

答案 5 :(得分:0)

如果你想删除每次点击文本的第一个字符,你可以使用子字符串。 e.g:

$("#textDiv").click(function(){
  $(this).html($(this).text().substring(1));
});

答案 6 :(得分:0)

要补充Jonathan的答案,请使用..

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

删除最后一个字符

答案 7 :(得分:0)

普通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>

答案 8 :(得分:-1)

使用属性$ = CSS3选择器很简单,这意味着在jQuery选择中“以...结尾”:

删除第一个字符:

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

要删除最后一个字符:

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