[英]Javascript replace some parts of string
我需要使用 javascript 隱藏部分字符串,我有電子郵件:
hideparts@email.com
我需要轉變為:
hi****@email.com
我需要在@ 之后顯示電子郵件,但我不知道如何執行此操作。
RegExp 可能很好。 Regex Editor
。
保留前兩個字母並替換@
之前的其余字母被替換
let str = 'hideparts@email.com'; console.log(str.replace(/(\\w{2}).*?@/, '$1****@'));
這是使用 map() 和 repeat() 的快速方法
let email = "hideparts@email.com"; const obfuscate = str => str.split('@').map((e, i) => i === 0 ? e.slice(0, 2) + '*'.repeat(e.length - 2) : e).join('@'); console.log(obfuscate(email))
首先獲取 @With 的索引
Var ind =str.indexof("@")
然后從索引 2 循環到 ind,每個循環用 * 替換這個字符
我覺得這可以使用indexOf()
和 for 循環來實現。
let email = 'hideparts@email.com'; let atPosition = email.indexOf('@'); //get @ position let startIndex = atPosition > 2 ? 2: 0; //handle case for really small email names if(atPosition > -1){ for(let i = startIndex ; i < atPosition;i++){ email = email.substring(0, i) + '*' + email.substring(i + 1); } } console.log(email);
使用.subtstring()
方法替換字符串中的字符。 email[i] = '*'
不起作用,字符串是不可變的。
您可以使用以下代碼來實現您的需求。
const str = 'abcdefgh@email.com'; const [contact, domain] = str.split('@'); const maskedMailId = contact.slice(0, 2) + '*'.repeat(contact.length - 2) + '@' + domain; console.log(maskedMailId);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.