Mask //JavaScript Repository

Description

Applies a mask on a string.
Created: 2005.10.02

Code (Download)

//+ Carlos R. L. Rodrigues
//@ http://jsfromhell.com/string/mask [rev. #1]

String.prototype.mask = function(m) {
    var m, l = (m = m.split("")).length, s = this.split(""), j = 0, h = "";
    for(var i = -1; ++i < l;)
        if(m[i] != "#"){
            if(m[i] == "\\" && (h += m[++i])) continue;
            h += m[i];
            i + 1 == l && (s[j - 1] += h, h = "");
        }
        else{
            if(!s[j] && !(h = "")) break;
            (s[j] = h + s[j++]) && (h = "");
        }
    return s.join("") + h;
};

Example (Example)

<script type="text/javascript">
//<![CDATA[

document.write(
    "\"", s = "12345678900", "\".mask(\"", m = "###.###.###,##", "\") = ", s.mask(m), "<br />",
    "\"", s = "1234", "\".mask(\"", m = "x:##, y: ##", "\") = ", s.mask(m), "<br />",
    "\"", s = "TEST", "\".mask(\"", m = "\\#-#*#/#^#", "\") = ", s.mask(m), "<br />"
);

//]]>
</script>

Help

String.mask(mask: String): String
Returns a string with the mask applied.
mask
mask that will be used

Observations

The mask replaces the ocurrences of "#" by the characters on the string, so if you need to use the character "#" as part of the mask, just comment it out with "\\". Example: "\\#".

The mask is applied from the left to the right, if the string has less characters than the mask, the "extra" characters of the mask will be ignored.

If the string has more characters than the mask, the remaining characters of the string will be added to the end of the mask.

Rank (Votes: 40)

4.03