Mask Javascript Variable Value
Solution 1:
There is a similar question (Javascript phone mask for text field with regex).
You can do it using regular expressions (see the code working at http://jsfiddle.net/BBeWN/45/):
var value = '1234567';
var formatted = value.replace(/^(\d{3})(\d{4}).*/, '$1-$2');
Notice that each part of the regular expression that is wrapped within parenthesis, (\d{3})
and (\d{4})
in the example above, can then be referenced to build the formatted text string using $1
and $2
respectively.
If you have N parts of the regular expression wrapped within parenthesis, you would be able to reference them to build a formatted text string with $1
, $2
, ..., $N
respectively.
So, for the other format you mention ((000) 000-0000), the code would be like this:
var formatted = value.replace(/^(\d{3})(\d{3})(\d{4}).*/, '($1) $2-$3');
You can find a great JavaScript regular expressions reference at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
Solution 2:
There is a javascript library that provides a solution for this problem:
https://github.com/the-darc/string-mask
And you don't need to create a new regular expression every time you change your mask(Format).
You can use it just like that:
var formatter = new StringMask("(000) 000-0000", { reverse: true });
var result = formatter.apply('123456789'); // (012) 345-6789
or
var formatter = new StringMask('#.##0,00', { reverse: true });
var result = formatter.apply('123456789'); // 1.234.567,89
Solution 3:
Here is a "mask" you may apply to a string of phone number digits of length 7 or 10 with an optional "+" to render it with dashes.
number.match(/^\+?([0-9]{3}){1,2}([0-9]{4})$/) || []).join('-')
Solution 4:
You can use my package https://github.com/jsonmaur/coverup, which can return the masked string as a variable.
Solution 5:
Using jsuites plugin you can do that
A) HTML
<html><scriptsrc="https://bossanova.uk/jsuites/v2/jsuites.js"></script><linkrel="stylesheet"href="https://bossanova.uk/jsuites/v2/jsuites.css"type="text/css" /><inputdata-mask='+44 0000 000 000'></html>
B) JAVASCRIPT
To get the parse a string into a variable
<script>var test = jSuites.mask.run('123456789', '(000) 000-0000');
console.log(test);
</script>
Post a Comment for "Mask Javascript Variable Value"