嗨,我有这个字符串 89 05 0342
。我想使用 regex 将其转换为 89-05-0342
。
我正在使用下面的代码,但其插入方式类似于 89-05-03-42
。任何人都可以帮助我获得正确的正则表达式来制作最终的字符串,例如 89-05-0342
我的代码
function copyPasteHandler() { //copy paste handler for textbox
var $this = $(this);
setTimeout(function () {
var Test = $this.val().replace(/ /g, '');
alert(Test);
if (Test.length < 10) {
Test = Test.match(new RegExp('.{1,2}', 'g')).join("-");
}
$this.val(Test);
}, 10);
}
最佳答案
如果您只想用破折号替换两个数字之间的空格,那么您可以使用以下命令:
alert(' 89 05 0342 '.replace(/(\d) (?=\d)/g, '$1-' )); // alerts ' 89-05-0342 '
此解决方案可确保不会触及任何其他空格,包括前导空格和尾随空格(如果存在)。
编辑:根据您的评论,我认为您想要的是删除前导和尾随空格,并用破折号替换所有内部空格,但前提是等效字符串 no 空格少于 10 个字符。您可以按如下方式执行此操作:
var str = ' 89 05 0342 ';
str = str.replace(/^\s+/,'').replace(/\s+$/,''); // remove leading/trailing whitespace
if (str.replace(/\s/g,'').length < 10) { // str length without whitespace must be < 10
str = str.replace(/\s+/g,'-'); // replace all extents of whitespace with a single dash
}
alert(str); // alerts '89-05-0342'
关于javascript - 使用正则表达式在字符串中的特定位置插入自动破折号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29162627/