我有一个字符串12345.00,我希望它返回12345.0。
我看了一下trim,但它看起来只是在修剪空白和切片,我不知道这是如何工作的。有什么建议吗?
我有一个字符串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
其他回答
试试看:
<script>
var x="foo_foo_foo_bar";
for (var i=0; i<=x.length; i++) {
if (x[i]=="_" && x[i+1]=="b") {
break;
}
else {
document.write(x[i]);
}
}
</script>
您也可以在http://jsfiddle.net/informativejavascript/F7WTn/87/.
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
if(str.substring(str.length - 4) == "_bar")
{
str = str.substring(0, str.length - 4);
}
通过切片(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");
1.(.*),多次捕获任何字符:
console.log(“字符串”.match(/(.*).$/)[1]);
2..,匹配最后一个字符,在这种情况下:
console.log(“字符串”.match(/(.*).$/));
3.$,匹配字符串的结尾:
console.log(“字符串”.match(/(.*).{2}$/)[1]);