如何使用jQuery删除字符串中的最后一个字符?

201

如何使用 jQuery 从字符串中删除最后一个字符,例如当我删除 4 后,它应该显示为 123-


36
那么您要删掉最后两个字符。 - Skilldrick
5个回答

510

你也可以尝试使用普通JavaScript实现此操作。

"1234".slice(0,-1)

负数第二个参数是距离最后一个字符的偏移量,因此您可以使用-2来删除最后两个字符等


18
现在我们(至少是我)经常使用jQuery,有时候会忘记如何用普通的JavaScript实现 =X。 - Michel Ayres
7
为了澄清事情(因为此帖子可能对初学者最有用):.slice()将返回结果。因此,应该使用: var result = "1234".slice(0,-1); - MMB

43

为什么要使用 jQuery?

str = "123-4"; 
alert(str.substring(0,str.length - 1));

当然,如果你必须这样做:

使用jQuery进行子字符串截取:

//example test element
 $(document.createElement('div'))
    .addClass('test')
    .text('123-4')
    .appendTo('body');

//using substring with the jQuery function html
alert($('.test').html().substring(0,$('.test').html().length - 1));

str.substring(0, str.count()-1): - GolezTrol
2
@GolezTrol:str.count()不是函数。str.length返回字符串中字符的数量。 - skajfes
@ skajfes 顺便说一句,这是一个更好的例子。我会编辑我的上面使用长度。 - Jason Benson
jQuery的好例子。感谢Jason的发布。最好的。 - OV Web Solutions
因为 jQuery 对于很多人来说更容易使用且更加合理。 - BevansDesign

9

@skajfes和@GolezTrol提供了最好的使用方法。个人而言,我更喜欢使用“slice()”。它的代码更少,并且您不需要知道字符串有多长。只需使用:

//-----------------------------------------
// @param begin  Required. The index where 
//               to begin the extraction. 
//               1st character is at index 0
//
// @param end    Optional. Where to end the
//               extraction. If omitted, 
//               slice() selects all 
//               characters from the begin 
//               position to the end of 
//               the string.
var str = '123-4';
alert(str.slice(0, -1));

我更喜欢使用子字符串。对我来说,切片太接近数组片了。 - Jason Benson

5
你可以使用纯JavaScript实现它:
alert('123-4-'.substr(0, 4)); // outputs "123-"

这将返回您字符串的前四个字符(根据您的需要调整4)。


3
使用slice(0, -1)解决方案更好,因为你不需要提前知道字符串的长度。 - Dan Dascalescu

1
这个页面是谷歌搜索“remove last character jquery”时的第一个结果。
尽管之前的所有答案都是正确的,但在快速简单地找到我想要的内容方面并没有帮助我。
我感觉还缺少一些东西。如果我重复了,请原谅。
jQuery
$('selector').each(function(){ 
  var text = $(this).html();
  text = text.substring(0, text.length-1);
  $(this).html(text);
});

$('selector').each(function(){ 
  var text = $(this).html();
  text = text.slice(0,-1);
  $(this).html(text);
})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接