用JavaScript替换最后4个字符以外的字符

时间:2019-04-18 16:01:28

标签: javascript

我正在一个项目上,想用JavaScript替换除最后4个字符以外的字符。需要一点帮助,谢谢

 var string = $('div.reg-summary-rows:nth-child(5) p:nth-child(2) span.reg-summary-answers').innerHTML;
 var len = string.length;
 var sub = len - 4;
 var string2 = "*****"
 var newString = string.slice(sub); 
document.querySelector("div.reg-summary-rows:nth-child(5) p:nth-child(2) span.reg-summary-answers").innerHTML = string2 ;

2 个答案:

答案 0 :(得分:1)

类似

const foo = '1234567890';
const limit = 4;
const head = foo.slice(0, -limit);
const tail = foo.slice(-limit);

console.log(head.replace(/./g, '*') + tail);

答案 1 :(得分:0)

一种可能的解决方案是通过以下方式使用replacement function中的String.replace()

const replaceAllExceptLast = (str, n) =>
{
    let token = "*";

    return str.replace(/./g, (match, offset) =>
    {
        return offset < str.length - n ?  token : match;
    });
}

console.log(replaceAllExceptLast("Hello World", 1));
console.log(replaceAllExceptLast("Hello World", 4));
console.log(replaceAllExceptLast("Hello World", 7));
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

请注意,正则表达式将匹配每个字符,但是只有在匹配元素的offset满足条件的情况下,我们才会进行替换。