我有一个字符串12345.00,我希望它返回12345.0。

我看了一下trim,但它看起来只是在修剪空白和切片,我不知道这是如何工作的。有什么建议吗?


当前回答

debris = string.split("_") //explode string into array of strings indexed by "_"

debris.pop(); //pop last element off the array (which you didn't want)

result = debris.join("_"); //fuse the remainng items together like the sun

其他回答

对于像您这样的数字,我建议对子字符串执行以下操作:

console.log(parseFloat('12345.00').toFixed(1));

请注意,这实际上会将数字四舍五入,我认为这是需要的,但可能不是:

console.log(parseFloat('12345.46').toFixed(1));

怎么样:

让myString=“12345.00”;console.log(myString.substring(0,myString.length-1));

debris = string.split("_") //explode string into array of strings indexed by "_"

debris.pop(); //pop last element off the array (which you didn't want)

result = debris.join("_"); //fuse the remainng items together like the sun

https://stackoverflow.com/questions/34817546/javascript-how-to-delete-last-two-characters-in-a-string

如果不需要空间,只需使用修剪

"11.01 °C".slice(0,-2).trim()

@杰森S:你可以用切片!你只需要确保你知道如何使用它。正数与开始,负数是相对于末端。js>“12345.00”.切片(0,-1)12345

对不起,我的写手,但帖子早些时候被标记为“jquery”。因此,不能在jQuery中使用slice(),因为slice(()是jQuery方法,用于使用DOM元素的操作,而不是子字符串。。。换言之,回答@Jon Erickson提出了非常完美的解决方案。

然而,您的方法将在简单的Javascript中使用jQuery函数。需要指出的是,由于上次在评论中的讨论,jQuery是JS的可更新扩展,而不是他自己的父级最著名的ECMAScript。

这里还存在两种方法:

作为我们的:

string。substring(from,to)as plus if“to”index null返回字符串的其余部分。因此:string.substring(from)正或负。。。

而其他一些-substr()-提供子字符串的范围,“length”只能为正:string.substr(开始,长度)

还有一些维护人员建议,最后一个方法string.substr(start,length)不起作用,或者对MSIE有错误。