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

如何基于API返回的掩码动态格式化输入框内容?

自定义掩码格式化函数实现方案

你遇到的是固定占位符(#)+ 固定字符的掩码场景,这类需求不需要依赖正则式掩码库,自己写个轻量函数就能搞定——核心逻辑是把用户输入的数字按顺序填充到掩码的#位置,其他固定字符直接保留。

核心函数实现

function formatWithMask(input, mask) {
  // 过滤输入中的非数字字符,转为数组方便逐个取用
  const digits = input.replace(/\D/g, '').split('');
  let result = '';
  let digitIndex = 0;

  // 遍历掩码的每一个字符
  for (const char of mask) {
    if (char === '#') {
      // 还有剩余数字的话,填充到当前#位置
      if (digitIndex < digits.length) {
        result += digits[digitIndex];
        digitIndex++;
      } else {
        // 数字用完了,停止填充后续的#
        break;
      }
    } else {
      // 非#字符直接加入结果
      result += char;
    }
  }

  return result;
}

示例用法

  • 完整输入场景:

    const mask = '(##)####-####';
    const userInput = '55999998888';
    console.log(formatWithMask(userInput, mask)); // 输出: (55)9999-8888
    
  • 输入过程中的部分格式化:

    console.log(formatWithMask('55999', mask)); // 输出: (55)999
    console.log(formatWithMask('5', mask)); // 输出: (5
    
  • 输入数字超过掩码长度的情况:

    console.log(formatWithMask('559999988887777', mask)); // 输出: (55)9999-8888(多余数字被截断)
    

输入框集成示例

可以把函数绑定到输入框的input事件,实时格式化内容,同时处理光标位置避免跳转:

const inputElement = document.getElementById('phone-input');
let currentMask = '(##)####-####'; // 从API获取的掩码

inputElement.addEventListener('input', (e) => {
  const originalValue = e.target.value;
  const formattedValue = formatWithMask(originalValue, currentMask);
  
  // 记录并调整光标位置
  const cursorPosition = e.target.selectionStart;
  const lengthDiff = formattedValue.length - originalValue.length;
  let newCursorPos = cursorPosition + lengthDiff;
  newCursorPos = Math.max(0, Math.min(newCursorPos, formattedValue.length));

  e.target.value = formattedValue;
  e.target.setSelectionRange(newCursorPos, newCursorPos);
});

内容的提问来源于stack exchange,提问作者Nathan Moreira

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 14:01:42