使用正则表达式在字符串中的特定位置插入自动短划线

时间:2015-03-20 08:51:04

标签: javascript jquery regex

嗨,我有这个字符串89 05 0342。我想使用正则表达式将其转换为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); 

               }

3 个答案:

答案 0 :(得分:0)

如果您只想用短划线替换两位数之间的空格,那么您可以使用:

&#13;
&#13;
alert(' 89 05 0342 '.replace(/(\d) (?=\d)/g, '$1-' )); // alerts ' 89-05-0342 '
&#13;
&#13;
&#13;

此解决方案可确保不会触及任何其他空格,包括前导和尾随空格(如果存在)。

编辑:根据您的评论,我认为你想要的是删除前导空格和尾随空格,并用短划线替换所有内部空格,但仅限于 no的等效字符串空格少于10个字符。你可以这样做:

&#13;
&#13;
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'
&#13;
&#13;
&#13;

答案 1 :(得分:0)

alert( '89 05 0342'.replace(/\s/g, '-') );

答案 2 :(得分:0)

您可以使用此替换:

var Test = $this.val().replace(/\s+/g, '-');

这将用单个连字符替换数字之间的一个或多个空格。