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

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

352883 次浏览

Why use jQuery for this?

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

Of course if you must:

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

You can do it with plain JavaScript:

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

This returns the first four characters of your string (adjust 4 to suit your needs).

You can also try this in plain javascript

"1234".slice(0,-1)

the negative second parameter is an offset from the last character, so you can use -2 to remove last 2 characters etc

@skajfes and @GolezTrol provided the best methods to use. Personally, I prefer using "slice()". It's less code, and you don't have to know how long a string is. Just use:

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

This page comes first when you search on Google "remove last character jquery"

Although all previous answers are correct, somehow did not helped me to find what I wanted in a quick and easy way.

I feel something is missing. Apologies if i'm duplicating

jQuery

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

or

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