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

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


当前回答

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

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

其他回答

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

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

最简单的方法是使用字符串的切片方法,该方法允许负位置(对应于从字符串末尾的偏移):

const s = "your string";
const withoutLastFourChars = s.slice(0, -4);

如果需要更一般的方法来删除最后一个下划线之后的所有内容(包括),可以执行以下操作(只要确保s至少包含一个下划线):

consts=“your_string”;const withoutLastChunk=s.slice(0,s.lastIndexOf(“_”));console.log(不带LastChunk);

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

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

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

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

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

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

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