How to use JS to change the middle four digits of mobile phone number into *

  • 2021-08-28 19:03:22
  • OfStack

Inadvertently noticed an interview question, the demand is to use js to change the middle 4 digits of the mobile phone number into *, and simply record 1.

1. Returns a character from a specified position to a specified number of characters in a string using the string's substr method substr ().

Syntax: str. substr (start [, length])

Parameter

start: The position at which character extraction begins. 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. Using the substring method for strings, the substring () method returns a subset of a string from the beginning index to the end index, or from the beginning index to the end of the string.

Syntax: str. substring (indexStart [, indexEnd])

Parameter

indexStart: The index of the first character to be truncated, and the character at this index position is used as the first letter of the returned string. indexEnd: Optional. 1 integer from 0 to the length of the string, and characters indexed by this number are not included in the truncated 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 contents as an array. This method changes the original array.

Syntax: array. splice (start [, deleteCount [, item1 [, item2 [, …]]]]])

Parameter

start: Specifies the starting position of the modification (count from 0). deleteCount: Optional, integer indicating the number of array elements to remove. item1, item2,... optionally, the elements to be added to the array start at the start position.

Return value

An array of deleted elements. If only 1 element is deleted, an array containing only 1 element is returned. If no element is 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. Using 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

Summarize


Related articles: