String manipulation is a common practice in day to day development. There is a full host of different variations when it comes to interacting with string values. When looking to insert a full word into an existing string it might not be as obvious as adding individual characters.
- The plus (+) operator
- Concat method
- Replace method
Let’s say we have the following strings
const name = "Tommy Vercetti"; const quote = ', remember the name.'
lastName into the start of the quote using these methods.
The easiest and fastest method is the + operator. Let’s add the word to the start of the quote:
const fullQuote = name += quote // "Tommy Vercetti, remember the name."
Keep in mind, that concat isn’t the best due to performance reasons:
It is strongly recommended to use the string concatenation operators (+, +=) instead of this method for perfomance reasons
However, its’ still viable:
const fullQuote = name.concat(quote); // "Tommy Vercetti, remember the name."
Okay so we’ve added the name but what if we want to add at the end?
While using the + operator is probably the most straightforward method, its not ideal being confined to adding to the beginning of a string. Lets solve this using replace.
const fullQuote = quote2.replace('.', ' ' + name ); // , remember the name Tommy Vercetti
And there you have it. I hope this helps.