【发布时间】:2010-11-29 22:55:31
【问题描述】:
当我删除 4 时,如何从字符串中删除最后一个字符,例如 123-4-,它应该使用 jQuery 显示 123-。
【问题讨论】:
-
那么您将删除最后两个字符。
标签: jquery
当我删除 4 时,如何从字符串中删除最后一个字符,例如 123-4-,它应该使用 jQuery 显示 123-。
【问题讨论】:
标签: jquery
你也可以用纯javascript试试这个
"1234".slice(0,-1)
第二个负参数是最后一个字符的偏移量,所以你可以使用 -2 来删除最后两个字符等
【讨论】:
为什么要为此使用 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));
【讨论】:
@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));
【讨论】:
你可以用纯 JavaScript 来做到这一点:
alert('123-4-'.substr(0, 4)); // outputs "123-"
这将返回字符串的前四个字符(调整 4 以满足您的需要)。
【讨论】:
当您在 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);
})
【讨论】: