从参数中删除空格到JS函数中

时间:2016-05-29 16:49:48

标签: javascript

我正在尝试使用trim()方法从HTML表单传递给函数的参数中删除空格。然后,该函数列出与该邮政编码匹配的地址。

var postCodes = {
  N48LP: {
    address: ['59, White Gardens', '54, White Gardens', '52, White Gardens', '55, White Gardens']
  }
};

function searchCode(arg2){
  arg2.trim();
if(typeof postCodes[arg2] === 'undefined') {
  document.getElementById('oldpa').innerHTML = 'Postcode not found';
} else {
// code here which prints the list of addresses
     }}};

这不起作用。 'N48LP'工作的地方,'N4 8LP'或'N 48LP'将导致'找不到邮政编码'。谁能告诉我为什么?非常感谢。

4 个答案:

答案 0 :(得分:4)

尝试替换而不是修剪。

var House = function(x, y) {
    var _posX;
    var _posY;

    function init(x,y) {
        _posX = x;
        _posY = y;
    }

    // Auto init
    init(x, y);


    // Public
    return {
        posX: _posX,
        posY: _posY,

        setPosition: function(x, y) {
            _posX = x;
            _posY = y;
        }
    };
};

答案 1 :(得分:3)

您正在寻找:arg2.split(' ').join('')trim函数仅从字符串的开头和结尾删除空格

答案 2 :(得分:2)

您的代码中存在几个问题。一个是trim()没有就地修剪字符串,这意味着它不会改变原始字符串。第二个是trim()不会删除字符之间的空格。

要解决此问题,您可以将replace()与正则表达式一起使用,将所有空格的所有出现替换为空字符串,然后将此值指定为在检查postCodes对象时要使用的索引。



var postCodes = {
  N48LP: {
    address: ['59, White Gardens', '54, White Gardens', '52, White Gardens', '55, White Gardens']
  }
};

function searchCode(arg2) {
  // note that you have to make the regex to perform
  // a global search to make it function as a trim as well
  var index = arg2.replace(/\s+/g, '');
  if (typeof postCodes[index] === 'undefined') {
    document.getElementById('oldpa').innerHTML += 'Postcode not found';
  } else {
    // code here which prints the list of addresses
    document.getElementById('oldpa').innerHTML += [
      '<strong>input: ', arg2.replace(/\s+/g, '&nbsp;'), '</strong>',
      '<pre>', JSON.stringify(postCodes[index], 0, 4), '</pre>'
    ].join('');
  }
}

searchCode('N 48LP');
searchCode('  N48LP  ');
searchCode('  N 4 8 L P  ');
&#13;
<div id="oldpa"></div>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

问题出在arg2.trim();。正如@DontRelaX所说,trim()方法不会删除字符串中间的空格。另一个问题,考虑到这将是一个问题,trim()返回修改后的字符串,但不会影响sting itself的值。