Home > database >  Having trouble concatenating two strings in TypeScript
Having trouble concatenating two strings in TypeScript

Time:11-24

I am trying to concatenate two strings in TypeScript like this:

let string1 = new String("IdNumber: "   this.IdNumber);
let string2 = new String(this.notes);
this.notes = string1.concat(string2.toString());

The output I see for this.notes on line 3 is missing the original text from this.notes in string2. This is what I see in devTools for this.notes on line 3 when debugging:

"IdNumber: 524242

" 

when hovering over this.notes on line 2 in devTools it looks like this:

"testing

 testing 2

 testing 3"

I was hoping that this.notes on line 3 would look like this:

"IdNumber: 524242

 testing

 testing 2

 testing 3"

What am I doing wrong?

CodePudding user response:

I think a more ergonomic (if not idiomatic) approach would be using template literals, for example:

Code in TypeScript Playground

const example = {
  IdNumber: 524242,
  notes: 'testing\n\ntesting 2\n\ntesting 3',
  update () {
    this.notes = `IdNumber: ${this.IdNumber}\n\n${this.notes}`;
  },
};

console.log(example.notes); // "testing\n\ntesting 2\n\ntesting 3"
example.update();
console.log(example.notes); // "IdNumber: 524242\n\ntesting\n\ntesting 2\n\ntesting 3"

CodePudding user response:

For string concatenation it is recommended* to use Template Literals

let string1 = `IdNumber: ${this.IdNumber}`;
let string2 = `${this.notes}`;
this.notes = `${string1}${string2}`

* https://eslint.org/docs/latest/rules/prefer-template

  • Related