I am using regex in javascript and want to replace all the digits in a number except the last four with '#'
. I have figured out how to replace all the digits with '#'
, what do I do to not replace the last four? Here is my code so far. return cc.replace(/[0-9]/g, "#")
To match a literal space, you'll need to escape it: "\\ " . This is a useful way of describing complex regular expressions: phone <- regex(" \\(? #
RegEx can be effectively used to recreate patterns. So combining this with . replace means we can replace patterns and not just exact characters.
To remove all characters except numbers in javascript, call the replace() method, passing it a regular expression that matches all non-number characters and replace them with an empty string. The replace method returns a new string with some or all of the matches replaced.
For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group.
use this pattern
\d(?=\d{4})
and replace with #
Demo
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