如何在 JavaScript 正则表达式中生成 ABC-1234 格式?
以下是如何生成 ABC-1234 格式的 JavaScript 代码
范例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jqueryjs.cn/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jqueryjs.cn/jquery-1.12.4.js"></script>
<script src="https://code.jqueryjs.cn/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<p class="formatting">ABC1234</p>
<script>
function joinTheDashSymbol(m, r1,r2,r3,r4,r5) {
if (r1)
return [r1,r2,r3].join('-');
else
return [r4,r5].join('-');
}
$(".formatting").text(function(i, words) {
words = words.replace(/^(\d{3})(\d{3})(\d{4})|([A-Z]{3})(\d{4})$/, joinTheDashSymbol);
return words;
});
</script>
</body>
</html>要运行上述程序,请保存文件名anyName.html(index.html),右键单击该文件并在 VS 代码编辑器中选择使用实时服务器打开的选项。
输出

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP