簡體   English   中英

替換Json String中的密碼鍵值對

[英]Replace password key value pair in Json String

這里的問題是,如果我在字符串中找到密碼元素,我想將密碼值替換為“ **********”。

例如:字符串"{"element" : "test1", "password": "dfsdn653##"}"

應該替換為

"{"element" : "test1", "password": "********"}"
//OR
"{"element" : "test1", "password": ""}"

我嘗試使用正則表達式替換字符串,但是沒有用。

您可以使用padStart

 var a = { "element": "test1", "password": "dfsdn653##" } a.password = "".padStart(a.password.length, '*') console.log(JSON.stringify(a)) //Some fixed length to not give away the actual length a.password = "".padStart(7, '*') console.log(JSON.stringify(a)) 

您可以使用JSON.parse()將其轉換為對象,然后更改password創建一個password.length數組,並使用* fill()並將其join()

 let str = `{"element" : "test1", "password": "dfsdn653##"}`; let obj = JSON.parse(str); obj.password =Array(obj.password.length).fill('*').join(''); console.log(JSON.stringify(obj)); 

如果使用類似這樣的自定義功能,在輸入內容的長度上顯示字符串'············' ,例如'I Like Pizza'

var toAsterisk = function(string) {
  var asterisks = "";
  for(var i = 0; i > string.length; i++) {
    asterisks = asterisks + "·"
  }
}

如果您將字符串顯示為星號,但是要添加到另一個包含密碼的字符串中,那么您將能夠擁有隱藏的密碼。

(希望這可以幫助!)

嘗試這個 :

 var jsonStr = '{"element" : "test1", "password": "dfsdn653##"}'; var jsonObj = JSON.parse(jsonStr); if (jsonObj.hasOwnProperty('password')) { var res = jsonObj.password.split('').map(elem => elem = '*').join(''); jsonObj.password = res; } console.log(jsonObj); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM