Merging several strings into one in JavaScript
Last updated: March 23, 2022.
The need to merge several strings into one larger one is common in JavaScript.
In this article, we cover basic merging through to the creation of a reusable utility function for merging strings into comma-separated list.
Manual string merging
For basic manual merging, the addition operator (+) can be used to output a new value and the addition assignment operator (+=) to append a string to an existing one:
/* Merging with addition (+) and addition assignment (+=) */ let baseString = "This is a string"; let toMerge = "!"; // Addition: const newString = baseString + toMerge; // "This is a string!" // Addition assignment: baseString += toMerge; console.log(baseString); // "This is a string!"
If you have a longer list and want to insert spaces, you can use the addition operator, or, probably a better solution in this case, a string literal with the values interpolated:
/* Merge string items into comma-separated list */ const name1 = "Lisa"; const name2 = "Robin"; const name3 = "Anna"; /* Using addition */ name1 + ", " + name2 + " and " + name3 + "."; /* Interpolating values in a string literal */ `${name1}, ${name2} and ${name3}.}`;
This covers cases where the list length is small and therefore manageable, and the list length is known.
But what if one or neither of these are true?
Merging strings stored in an array
If your strings are stored in an array, there is a very easy way to merge these.
Just apply the .join() method to the array, passing in a string value to place between the items in the new string:
/* Merging string values in array with join */ const names = ["Sam", "Karen", "Thomas", "James"]; console.log(names.join('')); // "SamKarenThomasJames" console.log(names.join(' ')); // "Sam Karen Thomas James" console.log(names.join(', ')); // "Sam, Karen, Thomas, James" console.log("This year's winners are" + names.join(", ") + "."); // Output: "This year's winners are Sam, Karen, Thomas, James."
But notice problem with that final output?
If I print it directly to the DOM, it may not read correctly because there is no and before the final string item. Unless we are listing the names after a colon (in which case the solution is already sufficient), we’d like to include that and before the final item in the new string.
Inserting and in a comma-separated list
Before adding and before the final item in the merged string, we need to check if the length of names is greater than 1 (in which cases there are multiple names). If this is true, we can insert and by prepending the value "and "
before the final item in the array before the merge.
We also probably want to make sure there isn’t a comma before and. Otherwise, a list of two names would read "name1, and name2"
and not "name1 and name2"
. This is handled by the second if statement below:
/* Creating a comma-separated list with and */ let names = ["Sam", "Karen", "Thomas", "James"]; if (names.length > 1) { names[names.length-1] = "and " + names[names.length-1]; } let oneString = names.join(', '); // This if statement removes the final comma if names length is greater than 1 if (names.length > 1) { let firstPart = oneString.slice(0, oneString.lastIndexOf(',')); let secondPart = oneString.slice(oneString.lastIndexOf(',')+1, oneString.length); oneString = firstPart + secondPart; } console.log(oneString); // "Sam, Karen, Thomas and James"
Merging strings in non-array format into one
If your string data is stored in several variables, you cannot apply the .join() method.
The easiest way in this case is to place the values in a new array, so the .join() method can be applied:
/* Storing strings in an array manually */ const person1 = "Lisa" ; const person2 = "Lukas"; const person3 = "Anna"; /* Format to array and then use join */ const namesArray = [person1, person2, person3]; if (namesArray.length > 1) { namesArray[namesArray.length-1] = "and " + namesArray[namesArray.length-1]; } const namesJoined = namesArray.join(', '); console.log(namesJoined); // "Lisa, Lukas, and James"
If you have items stored in an object, you can use a for…in loop to iterate through the object keys, querying the object to get each value in each loop:
/* Extracting data from an object to an array */ const obj = { name1: "Lisa", name2: "Anna", name3: "Robin", name4: "Jessica", name5: "Francesco" } myArray = []; for (key in obj) { myArray.push(obj[key]); } console.log(myArray); // ["Lisa", "Anna", "Robin", "Jessica", "Francesco"]
If you are struggling to get some string data out of an object, you may want to read our posts on how to iterate through an object and ES6 object destructuring (i.e. saving data in objects to variables).
A reusable function for joining strings
A better way to join than writing the code above out each time is to create a reusable function that can be called upon when needed.
The joinString
function below accepts two arguments: a string or strings in an array and a join rule (what is usually passed in to the .join method).
Place the function in your script or import it using JavaScript modules, and you can then call upon it as many times as you need, without writing out the code every time:
The function:
/* A comma-separated list utility function */ function joinString(inputArray) { if (inputArray.length > 1) { inputArray[inputArray.length-1] = "and " + inputArray[inputArray.length-1]; } let oneString = inputArray.join(', '); /* This if statement remove the final comma if inputArray length is greater than 1 */ if (inputArray.length > 1) { let firstPart = oneString.slice(0, oneString.lastIndexOf(',')); let secondPart = oneString.slice(oneString.lastIndexOf(',')+1, oneString.length); oneString = firstPart + secondPart; } return oneString; }
Usage examples:
// Usage examples: joinString(["Lisa", "Alex"]); // "Lisa and Alex" joinString(["Lisa", "Alex", "Michael"]); // "Lisa, Alex and Michael" joinString(["Lisa", "Alex", "Michael", "Anna"]); // "Lisa, Alex, Michael and Anna"
Summary
Wanting to merge several string values into one, longer string is a commonly necessary operation in JavaScript.
The techniques for doing so range from simple merging using manual techniques. But when, working with dynamic or large amounts of data, automated techniques are needed.
Use the utility function for creating a comma-separated list (or write your own) and manual techniques for smaller merging operations to make light work of this in your future projects.
Related links
- MDN Web Docs: Array.prototype.join()
- W3Schools: JavaScript operators
- StackOverflow discussion: Most efficient way to concatenate strings in JavaScript?