简单的方式?你要么必须走字符串,要么使用一些奇特的正则表达式。
通常情况下,我们会使用正则表达式来解决这个问题,但是假设您对正则表达式不太了解(也许是一个糟糕的假设,但大多数人可以先阅读它们),并且在让你下面发生了什么希望,我写的程序上多:
<input type="text" class="formatted" />
$(document).ready(function(){
function applyMask(instr){
var pOut = [], delimitter = '-', format = 0, pSplit = 4, pMax = 6;
// There are a lot of ways to express this. I just chose one that should
// be understandable.
if ((instr.length > 0) && (instr[0].toUpperCase() == 'H'))
{
pSplit = 3;
pMax = 5;
}
pMax = Math.min(pMax, instr.length);
for (var i=0; i < pMax; i++)
{
if ((i==pSplit) && (instr[i] != delimitter))
{
pOut.push(delimitter);
}
else
{
pOut.push(instr[i]);
}
}
return pOut.join('');
}
$('.formatted').keyup(function(){
$(this).val(applyMask($(this).val()).toUpperCase());
});
});
这里有一个小提琴,甚至:http://jsfiddle.net/UdcND/
+1不仅需要时间来建立rege x,但为了帮助说明我的观点,即正则表达式会是令人讨厌的。 :) –
@John Green约定的XD,但它很有趣!这几乎就像一个数学谜题XD –
我真的希望这适用于显示错误后的格式。如果留下格式并且人们在键入时键入实际格式的类型,那将很酷。通常,当某人开始输入时,格式会被删除。 – RetroCoder