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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4308934/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:03:49  来源:igfitidea点击:

How to delete last character from a string using jQuery?

jquery

提问by wiki

How to delete last character from a string for instance in 123-4-when I delete 4it should display 123-using jQuery.

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

回答by skajfes

You can also try this in plain javascript

您也可以在纯 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

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

回答by Jason Benson

Why use jQuery for this?

为什么要为此使用 jQuery?

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

Of course if you must:

当然,如果你必须:

Substr w/ jQuery:

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

回答by OV Web Solutions

@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:

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

回答by jwueller

You can do it with plain JavaScript:

您可以使用纯 JavaScript 来实现:

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

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

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