tesicg
tesicg

Reputation: 4053

How to get rid of extra space in string literal?

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?

Upvotes: 0

Views: 579

Answers (3)

nick zoum
nick zoum

Reputation: 7285

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(" ");

Upvotes: 1

jo_va
jo_va

Reputation: 13964

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

Upvotes: 1

Ori Drori
Ori Drori

Reputation: 191976

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}` : ''}`;

Upvotes: 1

Related Questions