屏蔽JavaScript变量值 [英] Mask javascript variable value
问题描述
我想屏蔽我的javascript变量值.基本上,我正在获取变量中的电话号码字段值,获取后,我想用其他格式将其屏蔽.
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.
我尝试了 jquery Mask插件,但是它屏蔽了控件的字符串格式.但是我想将字符串屏蔽到变量中.
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.
例如:
让我有一个电话字符串"0000000000"
,我将其存储在变量中:-
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.mask('000-0000');2)数字= number.mask('(000)000-0000');
1) number = number.mask('000-0000'); 2) number = number.mask('(000) 000-0000');
推荐答案
There is a similar question (Javascript phone mask for text field with regex).
您可以使用正则表达式(请参见 http://jsfiddle.net/BBeWN/45/):
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');
请注意,在上面的示例中,用括号括起来的正则表达式的每个部分分别为(\ 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.
如果正则表达式的N个部分括在括号中,则可以引用它们以使用 $ 1
, $ 2
、.来构建格式化的文本字符串.., $ N
.
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.
因此,对于您提到的其他格式((000)000-0000),代码将如下所示:
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');
这篇关于屏蔽JavaScript变量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!