我们以手机号码344格式化显示为例
<view class="text-area"> 手机号:<input type="tel" placeholder="请输入手机号" maxlength="13" v-model="telPhone" @input="handleTelInput" /> </view>js方法
<script> export default { data() { return { title: 'Hello', telPhone: '', } }, methods: { handleTelInput(e) { var len = this.telPhone.length var reg = new RegExp("\\s", "g"); var mobile_ = ''; this.telPhone = this.telPhone.replace(reg, ""); for (var i = 0; i < len; i++) { if (i == 2 || i == 6) { // charAt(int index)方法是一个能够用来检索特定索引下的字符的String实例的方法。 //这里用来检索this.telPhone的index为2和6 mobile_ = mobile_ + this.telPhone.charAt(i) + " "; //当检索到2和6时,将原本的mobile_值加上新增的this.telPhone值再加一个" "后再赋值给mobile_自己 } else { mobile_ += this.telPhone.charAt(i); } } this.telPhone = mobile_ }, } } </script>
网友回复