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

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


当前回答

正则表达式是您要查找的:

让str=“foo_bar”;console.log(str.replace(/_bar$/,“”));

其他回答

您可以使用JavaScript字符串对象的substring方法:

s = s.substring(0, s.length - 4)

它无条件地从字符串s中删除最后四个字符。

但是,如果要有条件地删除最后四个字符,则仅当它们完全是_bar时:

var re = /_bar$/;
s.replace(re, "");

使用JavaScript的切片函数:

let string='foo_bar';string=string.spice(0,-4);//在此处切下最后四个字符console.log(字符串);

这可以用于删除任何长度字符串末尾的“_bar”。

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

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

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

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

正则表达式是您要查找的:

让str=“foo_bar”;console.log(str.replace(/_bar$/,“”));

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