簡體   English   中英

創建正則表達式以替換具有相同字符的字符串的每個匹配字符

[英]Creating a regex to replace each matched character of a string with same character

在我的應用程序中,我將一個字母數字字符串傳遞給我的函數。 此字符串通常為17個字符,但並非總是如此。 我正在嘗試編寫一個匹配除字符串中最后4個字符之外的所有字符的正則表達式,並用X替換它們(以掩蓋它)。

例如

Input: HGHG8686HGHG8686H

Output: XXXXXXXXXXXXX686H

我寫的正則表達式對字符串執行替換如下

[a-zA-Z0-9].{12}

碼:

const maskedString = string.replace(/[a-zA-Z0-9].{12}/g, 'X');

我遇到的問題是它只用單個X替換除字符串中的最后4個字符以外的所有字符。它不知道為每個匹配的字符執行此操作。 有任何想法嗎?

你可以在replace中使用一個函數來做到這一點,這樣的事情會做:

 var str = "HGHG8686HGHG8686H" var regexp = /[a-zA-Z0-9]+(?=....)/g; var modifiedStr = str.replace(regexp, function ($2) { return ('X'.repeat($2.length +1)); }); console.log(modifiedStr); 

向前看( ?=以確保至少有四個以下字符。

 const regex = /.(?=....)/g; // ^ MATCH ANYTHING // ^^^^^^^^ THAT IS FOLLOWED BY FOUR CHARS function fix(str) { return str.replace(regex, 'X'); } const test = "HGHG8686HGHG8686H"; // CODE BELOW IS MERELY FOR DEMO PURPOSES const input = document.getElementById("input"); const output = document.getElementById("output"); function populate() { output.textContent = fix(input.value); } input.addEventListener("input", populate); input.value = test; populate(); 
 <p><label>Input: </label><input id="input"></p> <p>Output: <span id="output"></span></p> 

非正則表達式解決方案:

 const test = "HGHG8686HGHG8686H"; function fix(str) { return 'X'.repeat(str.length - 4) + str.slice(-4); } console.log(fix(test)); 

你不會在IE中找到String#repeat

簡單版本:(更易於閱讀)

const maskedString = string.replace(/(.{4})$|(^(..)|(.))/g, 'X\1'); // or X$1

現在使用:[a-zA-Z0-9]

const maskedString = string.replace(/([a-zA-Z0-9]{4})$|(^([a-zA-Z0-9]{2})|([a-zA-Z0-9]{1}))/g, 'X\1'); // or X$1

注意:我在START PLUS TWO字符上匹配的原因是抵消第一場比賽。 (最后附加的最后4個字符。)

您可以使用以下方法實現:

  var str = "HGHG8686HGHG8686H" var replaced='' var match = str.match(/.+/) for(i=0;i<match[0].length-4;i++){ str = match[0][i] replaced += "X" } replaced += match[0].substr(match[0].length-4) console.log(replaced); 

暫無
暫無

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

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