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

wik*_*iki 175 jquery

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

ska*_*fes 437

你也可以在普通的javascript中试试这个

"1234".slice(0,-1)
Run Code Online (Sandbox Code Playgroud)

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

  • 我们(至少我)现在使用如此多的jQuery,有时我忘记了如何在普通的javascript = X中做 (14认同)
  • 澄清事情(因为这篇文章可能主要对初学者有用): .slice() 将返回结果。所以应该使用: var result = "1234".slice(0,-1); (4认同)

Jas*_*son 37

为什么要使用jQuery呢?

str = "123-4"; 
alert(str.substring(0,str.length - 1));
Run Code Online (Sandbox Code Playgroud)

当然,如果你必须:

Substr w/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));
Run Code Online (Sandbox Code Playgroud)

  • @GolezTrol:str.count()不是函数。str.length返回字符串中的字符数 (2认同)

OV *_*ons 8

@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));
Run Code Online (Sandbox Code Playgroud)


jwu*_*ler 5

您可以使用纯JavaScript执行此操作:

alert('123-4-'.substr(0, 4)); // outputs "123-"
Run Code Online (Sandbox Code Playgroud)

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

  • 切片(0,-1)解决方案更好,因为您不需要事先知道字符串长度. (3认同)