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

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


当前回答

1.(.*),多次捕获任何字符:

console.log(“字符串”.match(/(.*).$/)[1]);

2..,匹配最后一个字符,在这种情况下:

console.log(“字符串”.match(/(.*).$/));

3.$,匹配字符串的结尾:

console.log(“字符串”.match(/(.*).{2}$/)[1]);

其他回答

尝试使用toFixed

const str = "12345.00";
return (+str).toFixed(1);

您可以使用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”。

您可以使用substring函数:

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

这是公认的答案,但根据下面的对话,切片语法更加清晰:

让str=“12345.00”;str=str.slice(0,-1);console.log(str);

1.(.*),多次捕获任何字符:

console.log(“字符串”.match(/(.*).$/)[1]);

2..,匹配最后一个字符,在这种情况下:

console.log(“字符串”.match(/(.*).$/));

3.$,匹配字符串的结尾:

console.log(“字符串”.match(/(.*).{2}$/)[1]);