The string replacement cannot be reversed from thin air,
you need to save the original value somewhere.
You could use jQuery's .data(), for example.
Store the original value with .data('value', str),
and when the field receives the focus,
restore it from .data('value').
function getMaskedValue(str) {
var trailingCharsIntactCount = 4;
return new Array(str.length - trailingCharsIntactCount + 1).join('*') + str.slice(-trailingCharsIntactCount);
}
var $cc = $('.cc');
var str = $cc.val();
$cc.data('value', str);
$cc
.val(getMaskedValue(str));
.focus(function() {
$(this).val($(this).data('value'));
});
And as @aaron pointed out,
after focus is lost, you also want to restore the masked value:
$cc
.focus(function() {
$(this).val($(this).data('value'));
})
.blur(function() {
str = $(this).val();
$(this).data('value', str);
$(this).val(getMaskedValue(str));
});
He is also right that you don't need .data(),
you could store the real value in a variable.
It will be good to hide it within a closure.
(See fiddle.)
(function() {
function getMaskedValue(s) {
var masklen = s.length - 4;
return s.substr(0, masklen).replace(/./g, '*') + s.substr(masklen);
}
var $cc = $('.cc');
var value = $cc.val();
$cc
.val(getMaskedValue(value))
.focus(function() {
$(this).val(value);
})
.blur(function() {
value = $(this).val();
$(this).val(getMaskedValue(value));
});
})();
I also simplified the implementation of computing the masked value,
which should perform better, eliminating array operations.