Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
156
rated 0 times [  157] [ 1]  / answers: 1 / hits: 77839  / 11 Years ago, mon, july 15, 2013, 12:00:00

I want to mask my javascript variable value.Basically i am getting phone number fields value in variable and after getting it i want to mask it in some other format.



I have tried the jquery Mask plugin but its mask the control's string format.But i want to mask the string into the variable.



Ex:



Let i have a phone string 0000000000 and i am storing it in a variable :-



var number =0000000000


and after that i want to mask it in other formats.Like-



1) number = number.mask('000-0000');
2) number = number.mask('(000) 000-0000');


More From » variables

 Answers
7

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


[#76993] Saturday, July 13, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lawrencem

Total Points: 153
Total Questions: 102
Total Answers: 98

Location: Mauritania
Member since Sun, Oct 17, 2021
3 Years ago
lawrencem questions
;