SoFunction
Updated on 2025-03-01

JavaScript implements mobile phone number 3-4-4 format and controls the location of the cursor when adding and deleting new

JavaScript implements mobile phone number 3-4-4 format

It is relatively simple to implement the 3-4-4 format of mobile phone numbers. Listen to the input event, get the mobile phone number in real time, and then perform intercept and splicing operations based on the length of the mobile phone number to realize the processing of the mobile phone format. After implementing the format processing, we also need to support the cursor not to move to the end when the specified cursor is added and deleted, because the format of the mobile phone number resets us. After listening to the input event to reassign the value, the cursor will move to the last one. The solution to this problem is to record the cursor position and reset the cursor position after the value value format is reset. Okay, this is the idea. Without saying much, just enter the code.

// An highlighted block
 <input
  ref="inputRef"
  class="life-input"
  v-model="value"
  :maxlength="13"
  :placeholder="Hahahahahaha"
  :pattern="[0-9]*"
  @input="onInput"
 />

// javascript
onInput(){
 val = (/\D/g, '').substring(0, 11);
 const nowIndex = (this.$);
 if (valueLen > 3 && valueLen < 8) {
  = `${(0, 3)} ${(3)}`;
 } else if (valueLen >= 8) {
  = `${(0, 3)} ${(
  3,
  4
  )} ${(7)}`;
 } else {
  = val;
 }
 // Set the cursor position after reassignment(nowIndex, );
},

 getCursortPosition(element) {
 let CaretPos = 0;
 if () {
 // Support IE ();
 const Sel = ();
 ('character', -);
 CaretPos = ;
 } else if ( ||  === '0'){
 // Support firefox CaretPos = ;
 }
 return CaretPos
 },

 setCurIndex(nowIndex, value) {
 const len = ;
 setTimeout(() => {
 let pos = nowIndex;
 // Added new operations if (len > ) {
  if (nowIndex === 4 || nowIndex === 9) {
  pos += 1;
  }
 } else if (len > ) {
  // Delete operation  if (nowIndex === 4 || nowIndex === 9) {
  pos -= 1;
  }
 }
 this.$ = pos;
 this.$ = pos;
  = ;
 }, 0);
 },

Summarize

This is the article about JavaScript implementing mobile phone number 3-4-4 format and controlling the position of the cursor when adding and deleting new js mobile phone number 3-4-4 format content, please search for my previous article or continue browsing the related articles below. I hope everyone will support me in the future!