0

The code looks as following:

const documentSigner = `${parameters.signor.surname} ${parameters.signor.name} ${parameters.signor.patronymic || ''}`;

As you can see, if there is patronymic everything will be fine, but if there is not, there will be extra space.

How to manage with this?

tesicg
  • 3,971
  • 16
  • 62
  • 121
  • 2
    Possible duplicate of [How to remove leading and trailing white spaces from a given html string?](https://stackoverflow.com/questions/10032024/how-to-remove-leading-and-trailing-white-spaces-from-a-given-html-string) – Jota.Toledo Feb 14 '19 at 10:32
  • 1
    Possible duplicate of [Trim string in JavaScript?](https://stackoverflow.com/questions/498970/trim-string-in-javascript) – Peter B Feb 14 '19 at 10:35

3 Answers3

1

Move the extra space into the interpolation, and only if patronymic exists, add the space.

const { surname, name, patronymic } = parameters.signor;

const documentSigner = `${surname} ${name}${patronymic ? ` ${patronymic}` : ''}`;
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
1

You can use JavaScript's "StringBuilder", by adding the elements you want to print to an Array and then calling the Array.prototype.join method. This will concatenate all the elements into a single string separated by the string supplied to the join method.

This way you will not have to repeat the connector string and you can also more easily maintain / improve its functionality.

var text = [parameters.signor.surname, parameters.signor.name];
if(parameters.signor.patronymic) text.push(parameters.signor.patronymic);
const documentSigner = text.join(" ");
nick zoum
  • 7,216
  • 7
  • 36
  • 80
1

You can do this with a ternary and a nested template string to prepend a space to your variable if it isn't empty:

function complexString(val1, val2) {
  return `${val1}${val2 ? ` ${val2}` : ''}!`;
}

console.log(complexString('hello', 'world'));
console.log(complexString('hello', ''));

Or you can also insert the space between two parts using a logical and (&&):

function complexString(val1, val2) {
  return `${val1}${val2 && ' '}${val2}!`;
}

console.log(complexString('hello', 'world'));
console.log(complexString('hello', ''));

You might want to trim your variable for the tests to be robust:

`${val1}${val2 && val2.trim() ? ` ${val2}` : ''}!`;
`${val1}${val2 && val2.trim() && ' '}${val2}!`;
jo_va
  • 13,504
  • 3
  • 23
  • 47