Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace all characters in a string except first and last characters, using JavaScript

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?

like image 958
kait Avatar asked Oct 21 '25 02:10

kait


1 Answers

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)
like image 199
georg Avatar answered Oct 22 '25 15:10

georg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!