javascript - 如何将文本重新格式化为不同的模式?

标签 javascript jquery asp.net vb.net

如何编写代码以将 BBBBB-AAA 的模式更改为 0AAABBBBB?我使用的是 asp.net、vb.net 和 jQuery。

加拿大银行帐户路由号码的格式:

A Canadian routing number displayed on a check needs to be reformatted differently for electronic payments. If a check displays a routing number as BBBBB-AAA (where AAA indicates the Financial Institution and BBBBB is the branch), then the routing number must be changed to 0AAABBBBB to process the payment electronically. For example, if a check from an account issued by the Bank of Montreal showed the routing number 00011-001, then that number would need to be reformatted to 000100011 for the payment to be electronically processed.

我在 .aspx 页面上从用户那里获取数据:

<input id="txtBankCode" maxlength="9" required="required" />

我在 jQuery .js 页面上获取数据:

var bankCode = $("#txtBankCode").val()

我需要将 bankCode 重新排列为 0AAABBBBB 格式,而不是 BBBBB-AAA。我猜有些用户不会输入破折号,而有些用户会。我怎样才能做到这一点?

最佳答案

鉴于连字符是可选的,您不能依赖它的存在来分割字符串。因此,替代解决方案是使用正则表达式根据输入格式重新组织字符串。试试这个:

这是一个 JS 解决方案:

var bankCode = 'BBBBB-AAA';
bankCode = bankCode.replace(/^(\w{5})-?(\w{3})$/, '0$2$1');

console.log(bankCode);

VB 中的逻辑相同:

Dim bankCode As String = "BBBBB-AAA"
bankCode = Regex.Replace(bankCode, "^(\w{5})-?(\w{3})$", "0$2$1")

Console.WriteLine(bankCode)

关于javascript - 如何将文本重新格式化为不同的模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59900480/

相关文章:

asp.net - 如何从服务器控件中删除 'name' 属性?

asp.net - 在 ASP.Net 网站中包含带有自定义控件的 Javascript

javascript - 如何使用 JWT token 作为登录验证?

javascript - 自定义伪弹出窗口不显示背景

javascript - $(document).ready 无法在 ajax 页面中工作

javascript - 使用 jQuery 制作可点击的行并排除子元素

asp.net - 配置错误 : <compilation debug ="true" targetFramework ="4.0"> ASP. NET MVC3

javascript - 使用 JS 和 JQuery 播放和停止声音

javascript - 将 javascript 对象变量从一个 HTML 页面传递到另一个 HTML 页面

javascript - 根据元素中的单词更改图像 src