JS implementation replaces the middle part of the string with special symbols

I. Introduction

I believe that many people have encountered that sensitive information needs to be partially hidden, most of which are replaced by special symbols.

It's just that today I meet the requirement of front-end display. I just record the relevant JS for the convenience of next use.

2, JS part

/* Partial hiding
** str String to process
** frontLen  Top reserved
** endLen  Last few reserved
** cha  Replaced string
*/
function plusXing(str, frontLen, endLen,cha) {
    var len = str.length - frontLen - endLen;
    var xing = '';
    for (var i = 0; i < len; i++) {
        xing += cha;
    }
    return str.substring(0, frontLen) + xing + str.substring(str.length - endLen);
};    

3, Application example

 1 <!doctype html>
 2 <html lang="en">
 3  <head>
 4   <meta charset="UTF-8">
 5   <meta name="Generator" content="EditPlus®">
 6   <meta name="Author" content="">
 7   <meta name="Keywords" content="">
 8   <meta name="Description" content="">
 9   <title>Hidden character</title>
10   <script src="https://cdn.bootcss.com/jquery/1.10.2/jquery.min.js"></script>
11   <style>
12     div{
13         margin:20px;
14         padding:20px;
15     }
16     input[type='button']{
17         padding:10px;
18     }
19     #btn_div{
20         margin-left:100px;
21     }
22   </style>
23  </head>
24  <body>
25   <div>Before processing:<input type="text" id="num"/></div>
26 
27   <div id='btn_div'><input type="button" value="Hiding processing" onclick="yincang();"></div>
28 
29   <div>After processing:<span id="secret_num"></span></div>
30 
31   <script>
32         function yincang(){
33             var num=$('#num').val();
34             var secret_num=plusXing(num,3,4,'*');
35             $('#secret_num').text(secret_num);
36         };
37 
38         /* Partial hiding
39         ** str String to process
40         ** frontLen  Top reserved
41         ** endLen  Last few reserved
42         ** cha  Replaced string
43 
44         */
45         function plusXing(str, frontLen, endLen,cha) {
46             var len = str.length - frontLen - endLen;
47             var xing = '';
48             for (var i = 0; i < len; i++) {
49                 xing += cha;
50             }
51             return str.substring(0, frontLen) + xing + str.substring(str.length - endLen);
52         };
53   </script>
54  </body>
55 </html>
Hide partial string

4, Instance effect

  

 

 

Five, summary

In this way, the function of hiding some sensitive information displayed in the front end is realized.

In fact, this function can be fully implemented in the background, which should be more secure!

Tags: Javascript JQuery

Posted on Fri, 31 Jan 2020 18:00:26 -0500 by logicopinion