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

我有一些带有一些角色的DIV 。 每次点击DIV本身,如何从文本中删除最后一个字符?

删除第一个字符

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

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

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

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

替代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); }); 

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

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

      
this is my div

哦,对不起,你问jquery ……嗯,这就是你用直接javascript做的。

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

 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的解决方案和更多年的Web开发经验,:)

如果要删除每次单击文本的第一个字符,可以使用子字符串。 例如:

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

要补充乔纳森的答案,请使用..

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

删除最后一个字符

普通的JavaScript:

 
This is some text

通过使用属性$ = 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); });