0

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?

4
  • 1
    String objects in JavaScript are very rarely useful. They are not the same as string primitive values. Commented Nov 23, 2022 at 14:10
  • Please provide a self-contained minimal reproducible example that demonstrates your issue when pasted into a standalone IDE. Right now the this context is missing so it's hard to know what's going on. I concur that new String(...) is almost certainly not what you want to do; you could use just String(...) instead. But without being able to reproduce the issue, this is all just guesswork. Commented Nov 23, 2022 at 14:13
  • It might help if you could explain what you're trying to get that "IdNumber: " + this.IdNumber + this.notes wouldn't give you. Commented Nov 23, 2022 at 14:13
  • This code may not be good but I just realized that I made a mistake and was setting this.notes in a separate location that was overwriting what was being set here. It was still very helpful to see how to use the template literals instead of String objects. Commented Nov 23, 2022 at 16:28

2 Answers 2

2

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"

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.