How to add a Word to a String in JavaScript?

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.

So, how can you add a word to a string in JavaScript?

To add a word to a string in JavaScript we can use any concatenating (joining) based String method. These include:

  • The plus (+) operator
  • Concat method
  • Replace method

Let’s say we have the following  strings

const name = "Tommy Vercetti"; 
const quote = ', remember the name.'

Lets put firstName and lastName into the start of the quote using these methods.

Plus Operator

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."

Concat

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."

Using Replace

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.

Proudly published with Gatsby