【问题标题】:How to delete last character from a string using jQuery?如何使用jQuery从字符串中删除最后一个字符?
【发布时间】:2010-11-29 22:55:31
【问题描述】:

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

【问题讨论】:

  • 那么您将删除最后两个字符。

标签: jquery


【解决方案1】:

你也可以用纯javascript试试这个

"1234".slice(0,-1)

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

【讨论】:

  • 我们现在(至少我是)使用了这么多 jQuery,有时我忘记了如何用普通的 javascript =X
  • 澄清一下(因为这篇文章可能对初学者很有用):.slice() 将返回结果。所以应该使用: var result = "1234".slice(0,-1);
【解决方案2】:

为什么要为此使用 jQuery?

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

当然,如果你必须:

带有 jQ​​uery 的子字符串:

//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:str.count() 不是函数。 str.length 返回字符串中的字符数
  • @skajfes BTW 这是一个更好的例子,我将在上面编辑我的使用长度
  • jQuery 的好例子。感谢您发布杰森。最佳
【解决方案3】:

@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));

【讨论】:

  • 我自己更喜欢子字符串。切片对我来说太接近数组切片了
【解决方案4】:

你可以用纯 JavaScript 来做到这一点:

alert('123-4-'.substr(0, 4)); // outputs "123-"

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

【讨论】:

  • slice(0, -1) 方案更好,因为你不需要提前知道字符串长度。
【解决方案5】:

当您在 Google 上搜索“删除最后一个字符 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);
})

【讨论】:

    猜你喜欢
    • 2021-12-11
    • 2011-11-18
    • 2017-08-19
    • 2020-03-12
    • 2011-01-19
    • 2013-09-12
    相关资源
    最近更新 更多