简体   繁体   中英

React empty string appears as white space

I have the following code:

export const formatAddress = address => {
  const {
    flatName,
    buildingName,
    houseNumber,
    streetName,
    city,
    postCode
  } = address;
  return [
    flatName || '',
    buildingName || '',
    `${houseNumber || ''} ${streetName || ''}`,
    city,
    postCode
  ]
    .filter(val => val)
    .join('\n');
};

My problem is that when houseNumber is received undefined, the empty string it appears as a white space on my app. How can I resolve this issue? I've tried using.trim() but did not work and my app crashed. Any ideas?

instead of filter you can use map method:

 .map(val => val.toString().replace(/^\s+|\s+$/gm,''))

How about conditionally adding the space instead.

${houseNumber? houseNumber + ' ': ''}${streetName || ''} ${houseNumber? houseNumber + ' ': ''}${streetName || ''} ,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM