链接JS方法

时间:2013-01-10 14:49:51

标签: javascript jquery

如果字符串符合某种格式,我正在尝试在字符串中插入一些空格。具体来说,如果字符串只包含数字,并且长度恰好是五个字符,则应在第三个和第四个数字之间添加空格。

Here's my test case:

function codeAddress() {
    var num_regex = /^\d+$/,
            input = $("#distributor-search").val(),
          address = (input.match(num_regex) && input.length == 5) ? input.split('').splice(3, 0 , ' ').join() : input ;

    console.log('The address is: ' + address);

    return false;
}

出于某种原因,链接.split().splice().join()似乎没有返回任何内容。我哪里错了?

4 个答案:

答案 0 :(得分:6)

split()返回一个数组,splice()返回带有已移除元素的数组,join()返回已加入的数组。

splice()看起来一切都出错了。您可以获取已删除的项目,而不是提供余数。

我的测试:

var input = '123,789';
var output = input.split(',').splice(1, 0, '456').join(',');

console.log(output); // outputs nothing, because `splice(1, 0, '456')` doesn't remove any values

你可以通过制作一个使用splice功能的原型来解决这个问题,如下所示:

Array.prototype.isplice = function() {
    var tmp = this;

    Array.prototype.splice.apply(tmp, Array.prototype.isplice.arguments);

    return tmp;
};

var output = input.split(',').isplice(1, 0, '456').join(',');
console.log(output); // outputs ["123", "456", "789"] as expected

答案 1 :(得分:2)

为什么不直接使用正则表达式?

var num_regex = /^(\d\d\d)(\d\d)$/,
        input = $("#distributor-search").val(),
      address = input.match(num_regex);
if (address) address = address[1] + ' ' + address[2];

该正则表达式匹配一个五位数的字符串,并将前三个和后两个数字组合在一起。如果测试字符串匹配,则.match()函数返回一个数组,其中两个组位于位置1和2(位置0是整个匹配)。

答案 2 :(得分:2)

正如其他人所解释的那样,你的函数不起作用,因为.splice()返回被删除的元素,而不是结果数组。

请尝试使用此正则表达式:

/^(\d\d\d)(\d\d)$/

如果长度为5位,它只会匹配一个字符串,它不会修改其他字符串。

示例:

var s = '123456'.replace(/^(\d\d\d)(\d\d)$/, '$1 $2');
// "123456"
var s = '1234'.replace(/^(\d\d\d)(\d\d)$/, '$1 $2');
// "1234"
var s = '12345'.replace(/^(\d\d\d)(\d\d)$/, '$1 $2');
// "123 45"

所以,在你的情况下:

address = $("#distributor-search").val().replace(/^(\d\d\d)(\d\d)$/, '$1 $2');

答案 3 :(得分:1)

在您的情况下,您无法将拼接与连接连接起来:

splice(3, 0 , ' ').join()

请记住,splice返回一个包含已删除项目的新数组,而不是结果数组。

相关问题