im trying to find if there is any javascript to format a string for display, so for exam "1234"- or any string over length 2- would become 12** i know there is a replace method but not sure how this would work. any suggestions welcome. thanks much
Assuming you want to mask the equivalent number of characters you can replicate * length - 2
times & append the 1st 2 characters of the original string;
var str = "123456";
var numCharsToKeep = 2;
if (str.length > numCharsToKeep)
str = str.substr(0, numCharsToKeep) + Array(str.length - numCharsToKeep + 1).join("*")
== "12******"
-
quick question im assuming its the array function that will cause it to replicate the "*" the required amount of times – chloe Jan 23 '12 at 15:49
-
Yes;
Array(str.length - numCharsToKeep + 1)
makes an array with [string length - 2] empty elements (we+ 1
as arrays are 0 based) then joining the array to a string with*
as a delimiter delimits all the empty elements with "*". – Alex K. Jan 23 '12 at 15:52