2

I'm trying to remove whitespace from an argument passed by a HTML form into a function using the trim() method. The function then lists the addresses that match that postcode.

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
     }}};

This doesn't work. Where 'N48LP' works, 'N4 8LP' or 'N 48LP' will result in 'Postcode not found'. Could anyone tell me why? Many thanks.

simonb
  • 25
  • 4
  • trim() removes only whitespace from beginning and end of string, not from the middle of it. Use split/join or regexps to remove all whitespaces if this is really what you want. See this answer for details: http://stackoverflow.com/questions/1144783/replacing-all-occurrences-of-a-string-in-javascript – practical programmer May 29 '16 at 16:53

4 Answers4

4

Try replace instead of trim.

arg2.replace(/\s+/, ""); 
fyasir
  • 2,924
  • 2
  • 23
  • 36
3

you are looking for: arg2.split(' ').join(''). trim function remove spaces from start and from end of strings only

DontRelaX
  • 744
  • 4
  • 10
2

There are several problems in your code. One is that trim() does not trim the string in-place, this means that it does not mutate the original string. The second one is that trim() does not remove spaces in between characters.

To solve this, you can use replace() with a regex that replaces all occurence of all spaces as empty strings, and then assign such value as an index to be used when checking the postCodes object.

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  ');
<div id="oldpa"></div>
ryeballar
  • 29,658
  • 10
  • 65
  • 74
0

Problem is here arg2.trim();. As @DontRelaX said trim() methods does not remove white spaces in the middle of the string. And another problem, considering that this would be a problem, that trim() returns modified string, but does not effect the value of the sting itself.

Mantas Čekanauskas
  • 2,218
  • 6
  • 23
  • 43