寻求JavaScript replace方法替代方案 解决IBAN格式化兼容问题
替代JavaScript replace方法格式化IBAN的方案
针对你遇到的部分安卓设备(含Pixel 6)上IBAN格式化重复问题,可通过字符串遍历分割的方式替代原有的正则replace实现,避免正则全局匹配在特定环境下的异常触发:
修改后的格式化逻辑
核心思路:先过滤无效字符,再通过循环将字符串分割为每4个字符一组,最后拼接空格。
<template> <div class="form_container p-4"> <b-field label="IBAN" custom-class="is-small has-text-weight-light has-text-grey" class="has-text-left has-text-weight-light" > <b-input rounded v-model.trim="formatedIBAN" placeholder="IBAN" /> </b-field> </div> </template> <script lang='ts'> import { Component, Vue } from 'vue-property-decorator'; import IBAN from 'iban'; @Component export default class IbanTest extends Vue { public form: any = { iban: '', }; get formatedIBAN(): string { return this.form.iban; } set formatedIBAN(iban: string) { // 1. 转大写并过滤非字母数字字符(用数组遍历替代replace) const cleanedIBAN = [...iban.toUpperCase()] .filter(char => /[A-Z0-9]/.test(char)) .join(''); // 2. 分割为每4个字符一组,避免正则replace的全局匹配异常 const formattedChunks: string[] = []; for (let i = 0; i < cleanedIBAN.length; i += 4) { formattedChunks.push(cleanedIBAN.slice(i, i + 4)); } this.form.iban = formattedChunks.join(' ').trim(); } } </script>
方案优势
- 完全避免了
replace(/(.{4})/g, '$1 ')这种全局正则替换,减少了在双向绑定循环中触发重复渲染的概率 - 字符过滤用数组遍历实现,更稳定,适配更多环境
内容的提问来源于stack exchange,提问作者Vascob
相关产品推荐
相关产品推荐

