You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React输入框每6位数字后自动插入pattern与空格的实现问题

React 输入框自动按指定格式插入符号与空格解决方案

你的原代码仅实现了固定长度插空格的逻辑,未做指定pattern的格式转换,需要重写格式化函数,实现逻辑如下:

  • 第一步:先过滤输入值中所有非数字字符,排除之前插入的格式符号干扰
  • 第二步:将纯数字串按每6位为一组拆分,不足6位的部分单独保留
  • 第三步:对每组满6位的数字,按xxx-x~xx的规则转换格式
  • 第四步:所有转换后的组用空格拼接,末尾不足6位的数字直接追加
  • 额外适配:修复输入时光标自动跳转到末尾的交互问题,保证用户可在中间位置编辑
import { useState, useRef } from 'react';

const [inputVal, setInputVal] = useState("");
const inputRef = useRef(null);

const handleChange = (e) => {
  // 记录当前光标位置
  const cursorPos = e.target.selectionStart;
  const rawVal = e.target.value;
  const formattedVal = formatInput(rawVal);
  
  // 计算格式化后的光标偏移量,避免跳转
  const rawNumCount = rawVal.slice(0, cursorPos).replace(/\D/g, '').length;
  let newCursorPos = 0;
  let count = 0;
  for (let i = 0; i < formattedVal.length; i++) {
    if (/\d/.test(formattedVal[i])) count++;
    if (count === rawNumCount) {
      newCursorPos = i + 1;
      break;
    }
  }

  setInputVal(formattedVal);
  // 异步重置光标位置
  setTimeout(() => {
    inputRef.current?.setSelectionRange(newCursorPos, newCursorPos);
  }, 0);
};

// 核心格式化函数
function formatInput(str) {
  if (!str) return "";
  // 过滤所有非数字字符
  const pureNums = str.replace(/\D/g, '');
  const chunks = [];
  // 按每6位拆分数字串
  for (let i = 0; i < pureNums.length; i += 6) {
    const chunk = pureNums.slice(i, i + 6);
    if (chunk.length === 6) {
      // 满6位按xxx-x~xx格式化
      chunks.push(`${chunk.slice(0,3)}-${chunk[3]}~${chunk.slice(4,6)}`);
    } else {
      // 不足6位直接保留
      chunks.push(chunk);
    }
  }
  // 用空格拼接所有分组
  return chunks.join(' ');
}

return(
  <div>
   <input
      ref={inputRef}
      type="text"
      value={inputVal}
      onChange={handleChange}
    />
  </div>
);

验证示例:输入123456789123456789123456789,输出结果为123-4~56 789-1~23 456-7~89 123-4~56 789,完全匹配需求。

内容的提问来源于stack exchange,提问作者Hamidur Rahman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.10 18:33:02