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

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


当前回答

使用子字符串获取_bar左侧的所有内容。但首先必须在字符串中获取_bar的instr:

str.substring(3, 7);

3是起点,7是长度。

其他回答

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

通过切片(indexStart,indexEnd)方法-注意,这不会更改现有字符串,而是创建一个副本并更改副本。

console.clear();
let str = "12345.00";
let a = str.slice(0, str.length -1)
console.log(a, "<= a");
console.log(str, "<= str is NOT changed");

通过正则表达式方法-注意,这不会更改现有字符串,而是创建一个副本并更改副本。

console.clear();
let regExp = /.$/g
let b = str.replace(regExp,"")
console.log(b, "<= b");
console.log(str, "<= str is NOT changed");

通过array.splice()方法->这只适用于数组,它会改变现有的数组(所以要小心这个),您需要先将字符串转换为数组,然后再转换回来。

console.clear();
let str = "12345.00";
let strToArray = str.split("")
console.log(strToArray, "<= strToArray");
let spliceMethod = strToArray.splice(str.length-1, 1)
str = strToArray.join("")
console.log(str, "<= str is changed now");

您可以使用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);

使用正则表达式:

设aStr=“12345.00”;aStr=aStr替换(/.$/,'');控制台日志(aStr);

使用子字符串获取_bar左侧的所有内容。但首先必须在字符串中获取_bar的instr:

str.substring(3, 7);

3是起点,7是长度。