我有一个字符串12345.00,我希望它返回12345.0。
我看了一下trim,但它看起来只是在修剪空白和切片,我不知道这是如何工作的。有什么建议吗?
我有一个字符串12345.00,我希望它返回12345.0。
我看了一下trim,但它看起来只是在修剪空白和切片,我不知道这是如何工作的。有什么建议吗?
当前回答
1.(.*),多次捕获任何字符:
console.log(“字符串”.match(/(.*).$/)[1]);
2..,匹配最后一个字符,在这种情况下:
console.log(“字符串”.match(/(.*).$/));
3.$,匹配字符串的结尾:
console.log(“字符串”.match(/(.*).{2}$/)[1]);
其他回答
如果要删除接近字符串末尾的内容(对于大小可变的字符串),可以将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);
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/.
怎么样:
让myString=“12345.00”;console.log(myString.substring(0,myString.length-1));
如果要对浮点数进行通用舍入,而不是只修剪最后一个字符:
var float1 = 12345.00,
float2 = 12345.4567,
float3 = 12345.982;
var MoreMath = {
/**
* Rounds a value to the specified number of decimals
* @param float value The value to be rounded
* @param int nrDecimals The number of decimals to round value to
* @return float value rounded to nrDecimals decimals
*/
round: function (value, nrDecimals) {
var x = nrDecimals > 0 ? 10 * parseInt(nrDecimals, 10) : 1;
return Math.round(value * x) / x;
}
}
MoreMath.round(float1, 1) => 12345.0
MoreMath.round(float2, 1) => 12345.5
MoreMath.round(float3, 1) => 12346.0
编辑:保罗指出,这似乎有一个内置函数。这种解决方案显然比我的干净得多。使用parseFloat后跟toFixed