I need to write a solution in JavaScript to replace all the characters in a string with a *, except for the first and last characters. I'm not very familiar with RegEx but was trying to use the following to achieve the solution:
var regex = /\.(?=^)(?!=$)/;
const censored = w.replace(regex)
console.log(censored)
Any ideas on how I can achieve this?
The idea of using lookaheads is viable, let's correct a few mistakes:
var regex = /(?<!^).(?!$)/g;
var w = 'fork'
var censored = w.replace(regex, '*')
console.log(censored)
Do note, however, that lookbehinds (?<= and ?<!) are from ES 2018 and not universally supported yet. (As pointed out in another answer, you actually don't need a lookbehind here, a lookahead (?!^) would do as well). Stil...
You can also chop off the first char and replace the rest:
var w = 'fork'
var censored = w[0] + w.slice(1).replace(/.(?!$)/g, '*')
console.log(censored)
Finally, here's a way to do that without any regexes at all:
var w = 'fork'
var censored = w[0] + '*'.repeat(w.length - 2) + w.slice(-1)
console.log(censored)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With