我使用正则表达式进行格式化
<p class="phone">2124771000</p>
$(".phone").text(function(i, text) {
text = text.replace(/(\d\d\d)(\d\d\d)(\d\d\d\d)/, "$1-$2-$3");
return text;
});
使用以上示例我可以转换212-477-1000
<p class="phone">ABC1234</p>
现在我想使用上面的文字制作 ABC-1234 字符串。
测试环境:http://jsfiddle.net/Xxk3F/4237/
任何人都非常感谢,提前致谢
答案 0 :(得分:3)
以下将检查3个大写字母后跟4个数字:
$(".phone").text(function(i, text) {
text = text.replace(/([A-Z]{3})(\d{4})/, "$1-$2");
return text;
});
答案 1 :(得分:3)
如果你想在1个正则表达式中捕获它们。
您可以使用任一表达式|
例如
/^(\d{3})(\d{3})(\d{4})|([A-Z]{3})(\d{4})$/
function replacer(m, p1,p2,p3, p4,p5) {
if (p1) return [p1,p2,p3].join('-')
else return [p4,p5].join('-');
}
$(".phone").text(function(i, text) {
text = text.replace(/^(\d{3})(\d{3})(\d{4})|([A-Z]{3})(\d{4})$/, replacer);
return text;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="phone">ABC1234</p>
<p class="phone">1231231234</p>
<p class="phone">XYZ2345</p>
<p class="phone">9999999999</p>
答案 2 :(得分:2)
您可以针对ABC1234
尝试此操作:
$(".phone").text(function(i, text) {
text = text.replace(/([a-z]+(?=\d+))/i, "$1-");
return text;
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="phone">ABC1234</p>
&#13;
对于电话号码,请尝试:
$(".phone").text(function(i, text) {
text = text.replace(/(\d{3})(\d{3})(\d{4})/, "$1-$2-$3");
return text;
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="phone">2124771000</p>
&#13;
答案 3 :(得分:1)
你可以尝试这种模式
text = text.replace(/([a-zA-Z]+)(\d+)/, "$1-$2");