我需要将 10 位字符串格式化为这种格式:'(123) 456-7890'。但是,我需要在用户键入时发生这种情况。因此,如果用户只输入了 3 位数字,则输入应显示:'(123)'。如果他们输入了 5 位数字,则输入应显示:'(123) 45'
使用我当前的代码,格式仅在输入第 10 个字符后发生。我希望它从第三个字符开始格式化。
const phoneRegex = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/
const handleInput = (value) => {
return (
value.replace(phoneRegex, '($1) $2-$3')
)
}
class FindASubscriber extends React.Component {
constructor(props) {
super(props)
this.state = {
value: ''
}
}
render() {
const { label, placeholder, feedback } = this.props
const { value} = this.state
return (
<div className="find__a__subscriber">
<FlexGrid>
<FlexGrid.Col>
<FlexGrid.Row>
<Input
feedback={feedback}
label={label}
type="text"
pattern="[0-9]*"
placeholder={placeholder}
value={handleInput(value)}
maxLength="10"
onChange={
(event) => this.setState({value: …Run Code Online (Sandbox Code Playgroud)