【发布时间】:2017-06-08 07:08:09
【问题描述】:
我有这个函数可以在“。”之后使数字的尾随零变暗
例如
- 123.456000 -> 123.456000
- 100.0000 -> 100.0000
- 456.999990 -> 456.999990
- 333 -> 333
这个函数生成的最终html是这样的
123.456 <span class="trailing-zeros"> 000 </span>
这是实际代码
// Only fade trailing zeros if they are decimals
function fadeTrailingZeros (val) {
var str = val + ''
if (str.match(/\./)) {
return str.replace(/(0+)$/g, '<span class="trailing-zeros">' + '$1' + '</span>')
} else {
return str
}
}
正则表达式用分类跨度替换尾随零并创造奇迹。
现在我必须在 react 环境中使用它,这是展示/哑/无状态组件的完美案例。
import React from 'react'
export default function fadeTrailingZeros ({ value }) {
if (value.match(/\./)) {
const [prec, dec] = value.split('.')
const trailing = dec.replace(
/(0+)$/g,
<span className='trailing-zeros'>{ $1 }</span>
// ...woops! this cannot work with jsx since it's not a string
// to replace stuff into and $1 does mean nothing in there
)
return (<span>{value}.{trailing}</span>)
} else {
return (
<span>{value}</span>
)
}
}
我该怎么办?
【问题讨论】:
-
投反对票时是否愿意解释?
-
由于 React DOM 描述符是 JS 对象而不是字符串,所以不能使用标准的字符串替换。
标签: javascript regex reactjs number-formatting