[英]RegExp replace all letter but not first and last
I have to replace all letters of name on ****. 我必须替换****上的所有姓名字母。 Example:
例:
Jeniffer -> J****r 珍妮弗-> J **** r
I try $(this).text( $(this).text().replace(/([^\\w])\\//g, "*"))
我尝试
$(this).text( $(this).text().replace(/([^\\w])\\//g, "*"))
Also, if name is Ron -> R****n 另外,如果名称是Ron-> R **** n
You can use a regular expression for this, by capturing the first and last letters in a capture group and ignoring all letters between them, then using the capture groups in the replacement: 您可以为此使用正则表达式,方法是捕获捕获组中的第一个和最后一个字母,然后忽略它们之间的所有字母,然后在替换中使用捕获组:
var updated = name.replace(/^(.).*(.)$/, "$1****$2");
Live Example: 现场示例:
function obscure(name) { return name.replace(/^(.).*(.)$/, "$1****$2"); } function test(name) { console.log(name, "=>", obscure(name)); } test("Ron"); test("Jeniffer");
But it's perhaps easier without: 但是,如果没有以下内容,可能会更容易:
var updated = name[0] + "****" + name[name.length - 1];
Live Example: 现场示例:
function obscure(name) { return name[0] + "****" + name[name.length - 1];; } function test(name) { console.log(name, "=>", obscure(name)); } test("Ron"); test("Jeniffer");
Both of those do assume the names will be at least two characters long. 这两个都假定名称至少有两个字符长。 I pity the fool who tries this on Mr. T's surname.
我很可惜以 T先生的姓氏来尝试的傻瓜 。
Since, you need to have four asterisk on each condition, you can create a reusable function that will create this format for you: 由于每个条件上需要有四个星号,因此可以创建一个可重用的函数,该函数将为您创建此格式:
function replace(str){ var firstChar = str.charAt(0); var lastChar = str.charAt(str.length-1); return firstChar + '****' + lastChar; } var str = 'Jeniffer'; console.log(replace(str)); str = 'America'; console.log(replace(str))
Appears that you're looking for regex lookaround 似乎您在寻找正则表达式环顾
Regex: (?<=\\w)(\\w+)(?=\\w)
- group 1 matches all characters which follow one character and followed by another one. 正则表达式:
(?<=\\w)(\\w+)(?=\\w)
-基团1个匹配随后一个字符, 接着一个又一个的所有字符。
Tests: https://regex101.com/r/PPeEqx/2/ 测试: https : //regex101.com/r/PPeEqx/2/
More Info: https://www.regular-expressions.info/lookaround.html 更多信息: https : //www.regular-expressions.info/lookaround.html
Find first and last chars and append ****
to the first one and add the last one: 查找第一个和最后一个字符,并在第一个字符后加上
****
并添加最后一个:
const firstName = 'Jeniffer';
const result = firstName.match(/^.|.$/gi).reduce((s, c, i) => `${s}${!i ? `${c}****` : c }`, '');
console.log(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.