我有一个字符串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

其他回答

试试看:

const myString=“Hello World!”;console.log(myString.slice(0,-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, "");
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

如果要删除接近字符串末尾的内容(对于大小可变的字符串),可以将slice()和substr()组合起来。

我有一个动态构建的带有标记的字符串,其中有一个用逗号分隔的锚标记列表。字符串类似于:

var str = "<a>text 1,</a><a>text 2,</a><a>text 2.3,</a><a>text abc,</a>";

要删除最后一个逗号,我执行了以下操作:

str = str.slice(0, -5) + str.substr(-4);