我有一个字符串12345.00,我希望它返回12345.0。
我看了一下trim,但它看起来只是在修剪空白和切片,我不知道这是如何工作的。有什么建议吗?
我有一个字符串12345.00,我希望它返回12345.0。
我看了一下trim,但它看起来只是在修剪空白和切片,我不知道这是如何工作的。有什么建议吗?
当前回答
最简单的方法是使用字符串的切片方法,该方法允许负位置(对应于从字符串末尾的偏移):
const s = "your string";
const withoutLastFourChars = s.slice(0, -4);
如果需要更一般的方法来删除最后一个下划线之后的所有内容(包括),可以执行以下操作(只要确保s至少包含一个下划线):
consts=“your_string”;const withoutLastChunk=s.slice(0,s.lastIndexOf(“_”));console.log(不带LastChunk);
其他回答
if(str.substring(str.length - 4) == "_bar")
{
str = str.substring(0, str.length - 4);
}
您可以使用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);
https://stackoverflow.com/questions/34817546/javascript-how-to-delete-last-two-characters-in-a-string
如果不需要空间,只需使用修剪
"11.01 °C".slice(0,-2).trim()
正则表达式是您要查找的:
让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