The Wayback Machine - https://web.archive.org/web/20241127020024/https://www.geeksforgeeks.org/how-to-concatenate-strings-in-javascript/
Open In App

How to Concatenate Strings in JavaScript ?

Last Updated : 16 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

String concatenation refers to combining multiple strings into a single string. This operation is commonly used in programming to create dynamic strings by joining text fragments or variables.

Approaches to Concate String in JavaScript:

Using String concat() Method

The concat() method is used to join two or more strings without changing the original strings and returning a new string.

Syntax:

str1.concat( str2, str3, . . . , strN )

Example: In this example, we will concat the given string using the strings concat() method.

JavaScript
// JavaScript concat() method to
// merge strings together

// Original string
let str = 'Geeks';

// Joining the strings together
let value = str.concat('for', 'Geeks');

console.log(value);

Output
GeeksforGeeks

Using JavaScript + Operator

The + operator adds strings and returns the concatenated string. It is the easiest method for the concatenation of two strings.

Syntax:

let str = str1 + str2

Example: In this example, we will concate two string using + operator.

JavaScript
// JavaScript + Operator to
// Merge Strings

// Original string
let str1 = 'Geeks';
let str2 = 'for';
let str3 = 'Geeks';

// Joining the strings together
let str = str1 + str2 + str3;

console.log(str);

Output
GeeksforGeeks

Using JavaScript Array join() Method

The JavaScript Array join() Method is used to join the elements of an array into a string. The elements of the string will be separated by a specified separator and its default value is a comma ( , ).

Syntax:

array.join( separator )

Example: In this article we will concate strings present in an array.

JavaScript
// JavaScript program to join Strings 
// using array join() method
let arr = ['Geeks', 'for', 'Geeks'];

// Joining the strings using
// join() method
let str = arr.join('');

console.log(str);

Output
GeeksforGeeks

Using Template Literals (Template Strings)

Template literals, denoted by backticks, allow string interpolation and multiline strings. Concatenation is achieved by embedding variables or expressions within `${}` placeholders. This approach enhances readability and simplifies string concatenation in JavaScript, offering a concise and flexible solution.

Example: In this example The variables firstName and lastName hold the strings “Suresh” and “Raina” respectively. fullName combines these variables using template literals to create the string “Suresh Raina”,

JavaScript
const firstName = "Suresh";
const lastName = "Raina";

const fullName = `${firstName} ${lastName}`;

console.log(fullName);

Output
Suresh Raina

Using String fromCharCode and reduce

This method involves using Array.from to convert strings into an array of character codes, then using reduce to concatenate them. Although less common, it’s a creative way to concatenate strings.

Example: In this example, we will concatenate two strings using the String.fromCharCode method and reduce.

JavaScript
function concatenate(...strings) {
  return String.fromCharCode(
    ...strings.reduce((acc, str) => acc.concat(...[...str].map(char => char.charCodeAt(0))), [])
  );
}

let str1 = 'Geeks';
let str2 = 'for';
let str3 = 'Geeks';
let str = concatenate(str1, str2, str3);
console.log(str);

Output
GeeksforGeeks


Previous Article
Next Article

Similar Reads

How to Concatenate Strings in PHP ?
In PHP, strings can be concatenated using the( . operator). Simply place the " . " between the strings you wish to concatenate, and PHP will merge them into a single string. Using (.operator)In PHP, the dot (.) operator is used for string concatenation. By placing the dot between strings and variables, they can be combined into a single string. Thi
1 min read
How to concatenate regex literals in JavaScript ?
Regex is a sequence of pattern that is used for matching with a pattern. While searching for data in a text, the search pattern is described for what we are searching for. It can be a single character or a more complex pattern. It can be used to perform all types of text searches. Regex has its own static and instance properties. Syntax: /pattern/m
2 min read
How to Concatenate Two Variables in JavaScript ?
In JavaScript, you can concatenate two variables (combine their values into a single string) using the + operator. Example 1: Here, the + operator is used to concatenate the values of firstName, a space character, and lastName into the variable fullName. C/C++ Code let firstName = "John"; let lastName = "Doe"; le
1 min read
What is the most efficient way to concatenate N arrays in JavaScript ?
In this article, we will see how to concatenate N arrays in JavaScript. The efficient way to concatenate N arrays can depend on the number of arrays and the size of arrays. To concatenate N arrays, we use the following methods: Table of Content Method 1: Using push() MethodMethod 2: Using concat() MethodMethod 3: Using Spread OperatorMethod 4: Usin
3 min read
Tensorflow.js tf.data.Dataset.concatenate() Function
Tensorflow.js is an open-source library developed by Google for running machine learning models and deep learning neural networks in the browser or node environment. It also helps the developers to develop ML models in JavaScript language and can use ML directly in the browser or in Node.js. The tf.data.Dataset.concatenate() function is used to con
1 min read
Tensorflow.js tf.layers.concatenate() Function
Tensorflow.js is an open-source library developed by Google for running machine learning models and deep learning neural networks in the browser or node environment. The tf.layers.concatenate() function is used to concatenate an array of inputs. Syntax: tf.layers.concatenate() Parameters: args(Object): specifies the given object. It is an optional
2 min read
How to concatenate unicode and variable in ReactJS ?
Unicode is an encoding standard for all characters in the universe. Every language code and symbol in this world is assigned by Unicode. There is no encoding standard that supports all languages, By using the Unicode standard, we can retrieve and combine data with all language combinations. Example: In the above example, a right-facing arrow is rep
2 min read
How to Concatenate Two Arrays in PHP ?
Concatenating Arrays in PHP involves combining the elements of two or more arrays into a single array. This operation is useful when you need to merge multiple arrays to create a larger array containing all their elements. Using array_merge() Function array_merge( ) in PHP combines two or more arrays into a single array, preserving numeric keys and
1 min read
How to Concatenate Pipe Values in a String in Angular?
Pipes in Angular are features that let us transform the data into some other format in the templates. For example, converting a number into a currency, or a value into a date, etc. In this article, we will learn how to concatenate pipe value in a string with the help of a code example. Step 1: Initialising the projectLet's create an angular project
2 min read
Replace multiple strings with multiple other strings in JavaScript
In this article, we are given a Sentence having multiple strings. The task is to replace multiple strings with new strings simultaneously instead of doing it one by one, using JavaScript. Below are a few methods to understand: Table of Content Using JavaScript replace() method Using the JavaScript str.replaceAll() methodUsing Array.reduce() method:
2 min read
How to return all matching strings against a regular expression in JavaScript ?
In this article, we will learn how to identify if a string matches with a regular expression and subsequently return all the matching strings in JavaScript. We can use the JavaScript string.search() method to search for a match between a regular expression in a given string. Syntax: let index = string.search( expression )Parameters: This method acc
3 min read
Optimum way to compare strings in JavaScript
In this article, we will know the optimal way to compare the strings using built-in JavaScript methods & will see their implementation through the examples. The question is to compare 2 JavaScript strings optimally. To do so, here are a few of the most used techniques discussed. The method discussed below is used in the following examples. Stri
3 min read
What are the builtin strings in JavaScript ?
A sequence of letters, special characters, numbers, etc., or a combination of all of them is known as a string. Strings are created by enclosing the string characters within a single quote (') or within double quotes ("). Syntax: var myString = 'Good Morning123!'; // Single quoted string var myString = "Good Morning123!"; // Double quoted string In
3 min read
Which built-in method combines two strings and returns a new string in JavaScript ?
In this article, we will know how to combine the text of two strings and return the new string. There are two best-fit methods for this situation: JavaScript concat() methodJavaScript join() methodWe will explore both these methods & their implementations in detail & understand them through the examples. Using concat() method: The concat()
2 min read
Are JavaScript Strings mutable ?
JavaScript Strings are immutable since once a string is created it will receive a reference in the memory and its value will never change. This means that any operation on a string may give the new string without mutating the main string. There are some misconceptions that the string can be converted to uppercase or lowercase but in reality, if we
2 min read
JavaScript Strings Read Only
In this article, we will try to answer a major question that arises with working in JavaScript. Are the Strings read-only in JavaScript? In JavaScript Strings are a primitive data type that are used to store an array of characters. The Strings in JavaScript have a special trait that the strings are read-only. Read-only means that the strings create
2 min read
What is the use of Single Quotes ('') & Double Quotes ("") for Strings in JavaScript ?
In JavaScript, both single quotes ('') and double quotes ("") can be used to create strings, and they are interchangeable in most situations. However, there are a couple of differences worth noting: Quoting Inside Strings: If your string contains an apostrophe (single quote) and you use double quotes to define the string, you won't need to escape t
1 min read
JavaScript Program to Find Uncommon Characters of the two Strings
In JavaScript, finding uncommon characters in two strings is the process of identifying the characters that exist in one string but not in the other string. We can find these uncommon characters using various approaches that are mentioned below: Table of Content Using SetsUsing Array.filter() methodUsing Logical OR OperationUsing SetsIn this approa
2 min read
Javascript Program To Check Whether Two Strings Are Anagram Of Each Other
Write a function to check whether two given strings are anagram of each other or not. An anagram of a string is another string that contains the same characters, only the order of characters can be different. For example, "abcd" and "dabc" are an anagram of each other. We strongly recommend that you click here and practice it, before moving on to t
7 min read
JavaScript Program to Compare Two Strings Lexicographically
This JavaScript program compares two strings lexicographically, meaning it checks if one string comes before or after the other in alphabetical order. Lexicographical comparison is based on the Unicode value of each character in the strings. The program should return a positive value if the first string comes after the second string, a negative val
2 min read
JavaScript Program to Split a String into a Number of Sub-Strings
Given a string, the task is to split the string into number of sub-strings using JavaScript. This task is common in scenarios where data needs to be segmented or processed in chunks. This article provides a flexible solution that can divide a given string into a desired number of smaller substrings, allowing for efficient manipulation or analysis o
2 min read
Checking for Duplicate Strings in JavaScript Array
Checking for duplicate strings in a JavaScript array involves identifying if there are any repeated string values within the array. Given an array of strings a with size N, find all strings that occur more than once. If none is found, return [-1]. Example: Input: N = 4arr = ['apple', 'banana', 'orange', 'apple']Output :[ 'apple' ]Explanation : Ther
4 min read
Sorting Strings with Decimal Points in JavaScript
Sorting strings with decimal points in JavaScript can be done using the localeCompare method or a custom sorting function. Examples: Input: strings = ["2.5", "1.3", "3.2", "1.1", "2.1"]Output: ["1.1", "1.3", "2.1", "2.5", "3.2"]Input: ["2.7", "1.5", "3.6", "1.2", "2.1"];Output: ["1.2", "1.5", "2.1", "2.7", "3.6"]Table of Content Using localeCompare
2 min read
Group Strings Starting with Similar Number in JavaScript
Given an array of strings containing numbers at the beginning, the task is to group strings that start with the same number together. Examples: Input: arr = ["101apple", "202banana", "101orange", "303grape", "202mango", "101kiwi"];Output: [["101apple", "101orange", "101kiwi"],["202banana", "202mango"],["303grape"]]Explanation: In this example, the
3 min read
How to replace a portion of strings with another value in JavaScript ?
In JavaScript, replacing a portion of strings with another value involves using the `replace()` method or regular expressions. This process is essential for text manipulation tasks like formatting, sanitization, or dynamic content generation in web development and data processing applications. We can replace a portion of a string in multiple ways.
3 min read
How to create multi-line strings in JavaScript ?
In JavaScript, the absence of native support for multi-line strings was a longstanding challenge. However, with the advent of ES6 (ECMAScript 2015), the things changed dramatically. ES6 introduced string literals, offering robust support for multi-line strings, which was a significant enhancement for developers. In this article, we'll see the evolu
3 min read
JavaScript Program to Remove Empty Strings from Array Without Loop
Given an array with values and empty strings, our task is to remove empty strings from an array while keeping a record of the removed elements without using explicit loops. Example: Input: Array = ["hello", "", "world", "", "!", " "]; Output: Cleaned Array: [ 'hello', 'world', '!', ' ' ] Removed Elements: [ '', '' ]Below are the approaches to remov
3 min read
Check if two strings are permutation of each other in JavaScript
In this approach, we are going to discuss how we can check if two strings are permutations of each other or not using JavaScript language. If two strings have the same number of characters rather than having the same position or not it will be a permutation. Example: Input: "pqrs" , "rpqs"Output: TrueExplanation: Both strings have a same number of
4 min read
JavaScript Program to Add n Binary Strings
In this article, we are going to learn about Adding n binary strings by using JavaScript. Adding n binary strings in JavaScript refers to the process of performing binary addition on a collection of n binary strings, treating them as binary numbers, and producing the sum in binary representation as the result. There are several methods that can be
3 min read
JavaScript Program to Sort Strings in Alphabetical Order Ignoring Case
In this article, we are given an array of strings, you need to sort the given array of strings containing both uppercase and lowercase characters in ascending order by ignoring the case in JavaScript. Example 1: Input :- arr = ["Geeks", "for", "geeks", "is", "The", "Best"] Output :- [ 'Best', 'for', 'Geeks', 'geeks', 'is', 'The' ] Explanation: In t
3 min read
three90RightbarBannerImg