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


181

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


30
然后,您要删除最后两个字符。
Skilldrick 2010年

Answers:


459

您也可以尝试使用纯JavaScript

"1234".slice(0,-1)

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


15
我们(至少我现在)在使用大量的jQuery,有时我忘记了如何使用普通的javascript = X
Michel Ayres 2012年

2
为了弄清楚事情(因为这篇文章可能对初学者来说很有用):.slice()将返回结果。所以应该使用:var result =“ 1234” .slice(0,-1);
MMB

38

为什么要为此使用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,2010年

@ skajfes顺便说一句,这是一个更好的例子,我将在上面编辑我的文章以使用长度
Jason Benson 2010年

jQuery的好例子。感谢您发布Jason。最佳
OV Web Solutions 2010年

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 2010年

5

您可以使用普通的JavaScript来做到这一点:

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

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


3
slice(0,-1)解决方案更好,因为您不需要事先知道字符串长度。
Dan Dascalescu '16
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.