preface

This is not a serious article, but it may be useful to you.

Username – Only last name or middle characters are reserved for special handling

demand

When displaying user information, only the first and last name of the user should be displayed, and the middle one should be replaced by an *

  • Method 1: encapsulate the function and usesubstrIntercept string**

function formatName(name) {
  let newStr;
  if (name.length === 2) {
    newStr = name.substr(0, 1) + The '*'; // Truncate the string from bit 0 by substr  } else if (name.length > 2) {
// When the name is greater than 2 characters let char = ' ';  for (let i = 0, len = name.length - 2; i < len; i++) { // Loop over the string char += The '*';  }  newStr = name.substr(0, 1) + char + name.substr(-1, 1);  } else {  newStr = name;  }   return newStr; } console.log(formatName('Wang Hailong')); // Output wang * dragonCopy the code
  • Method 2: Use regular expressions to change only the last names to ‘***’

var str = 'Xiao Ming Wang';
var reg = /(? < =.) ./g;result = str.replace(reg, The '*');
console.log(result); / / * * kingCopy the code

The parentheses represent subexpressions, which are used to group and categorize subexpressions

? : matches zero or one character, that is, it can match only zero or one occurrence of a character (or a collection of characters), but not more than one occurrence

.: Matches characters other than newlines (that is, any single character, letters, numbers, underscores, even the character itself)

See regular expressions for more information

Regular expressions in js

The middle four digits of the mobile phone number are replaced by an asterisk (*)

When displaying user information, the mobile phone number belongs to private information, so the middle four digits need to be hidden

  • Method 1: Use regular expressions

var phone = '13701134148';
var resultPhone = phone.replace(/^(\d{3})\d{4}(\d+)/, '$1 $2 * * * *');
console.log(resultPhone); * * * * 4148 / / 137Copy the code
  • Method 2: String interception using the substr method

var phone = '13701134148';
var mphone = phone.substr(0, 3) + '* * * *' + phone.substr(7);
console.log(mphone);
// If you use Es6 template strings, you can concatenate them without the + signvar phone = '13701134148';
var mphone = `${phone.substr(0, 3)}* * * *${phone.substr(7)}`; Copy the code

In combination with the previous two examples, you can view the user name and mobile phone number instance application

More content, can go to coder.itclan.cn/, welcome students passing by to raise issue, soul torture