Use js to change the middle four digits of the mobile phone number to *

Preface: I accidentally noticed an interview question. The need is to use js to change the middle four digits of the mobile phone number to *, and simply record it.

1. Use string substr method

  • The substr() method returns the characters from the specified position to the specified number of characters in a string.
  • Syntax: str.substr(start[, length])
parameter
  • start: The position to start extracting characters.
  • length: Optional. The number of characters extracted.
	var tel = 15617076160;
	tel = "" + tel;
	var newTel = tel.substr(0,3) + "****" + tel.substr(7)
	console.log(newTel);//156****6160

2. The substring method using strings

  • The substring() method returns a subset of a string between the start index and the end index, or a subset from the start index to the end of the string.
  • Syntax: str.substring(indexStart[, indexEnd])
parameter
  • indexStart: The index of the first character to be intercepted, and the character at the index position is used as the first letter of the returned string.
  • indexEnd: optional. An integer between 0 and the length of the string. The character indexed by this number is not included in the intercepted string.
	var tel = 15617076160;
	tel = "" + tel;
	var newTel =tel.replace(tel.substring(3,7), "****")
	console.log(newTel);//156****6160

3. Using the array splice method

  • The splice() method modifies the array by deleting or replacing existing elements or adding new elements in place, and returns the modified content in the form of an array. This method will change the original array.
  • Syntax: array.splice(start[, deleteCount[, item1[, item2[, …]]]])
parameter
  • start​: Specify the start position of the modification (counting from 0).
  • deleteCount: Optional, integer, indicating the number of array elements to be removed.
  • item1, item2,… Optional, the elements to be added to the array start from the start position.
return value
  • An array of deleted elements. If only one element is deleted, an array containing only one element is returned. If no elements are deleted, an empty array is returned.
	var tel = 15617076160;
	tel = "" + tel;
	var ary = tel.split("");
	ary.splice(3,4,"****");
	var newTel=ary.join("");
	console.log(newTel);//156****6160

4. Use regular expressions

	var tel = 15617076160;
	tel = "" + tel;
	var reg=/(\d{3})\d{4}(\d{4})/;
	var newTel = tel.replace(reg, "$1****$2")
	console.log(newTel);//156****6160

Guess you like

Origin blog.csdn.net/dairen_j/article/details/108818752