This JavaScript tutorial explains how to use the string approach known as concat() with syntax and examples.
Description
In JavaScript, concat() is a string method that is used to concatenate strings together. The concat() technique appends one or extra string values to the calling string and then returns the concatenated end result as a new string. Because the concat() method is a method of the String object, it need to be invoked through a precise occasion of the String class.
Syntax
In JavaScript, the syntax for the concat() approach is:
string.concat(value1, value2, ... value_n);
Parameters or Arguments
value1, value2, … value_n The values to concatenate to the give up of string.
Returns
The concat() method returns a new string that consequences from concatenating the authentic string with the string values that were handed in as parameters.
Note
Each of the parameter values will be converted to a string, if necessary, before the concatenation operation is performed. The concat() technique does no longer exchange the cost of the original string. You can additionally use the + operator to concatenate values together.
Example
Let’s take a look at an example of how to use the concat() technique in JavaScript.
For example:
var totn_string = 'Tech';
console.log(totn_string.concat('On','The','Net'));
console.log(totn_string);
In this example, we have declared a variable known as totn_string that is assigned the string fee of ‘Tech’. We have then invoked the concat() approach of the totn_string variable to append the three string values to the cease of the value of the totn_string variable.
We have written the output of the concat() approach to the net browser console log, for demonstration purposes, to show what the concat() technique returns.
The following will be output to the net browser console log:
TechOnTheNet
Tech
As you can see, the concat() approach lower back the concatenated string cost of ‘TechOnTheNet’. This is the concatenation of the string ‘Tech’ + ‘On’ + ‘The’ + ‘Net’.
The value of the original totn_string variable has not modified and is nonetheless equal to ‘Tech’.
Concatenating with an Empty String Variable
You can use the concat() method with an empty string variable to concatenate primitive string values.
For example:
var totn_string = '';
console.log(totn_string.concat('Tech','On','The','Net'));
The following will be output to the web browser console log:
TechOnTheNet
By declaring a variable known as totn_string as an empty string or ”, you can invoke the String concat() technique to concatenate primitive string values together. This would be equivalent to the following:
console.log(''.concat('Tech','On','The','Net'));
The + operator is another way to concatenate string values together:
console.log('Tech' + 'On' + 'The' + 'Net');
The + operator approves you to concatenate strings barring the need for the String object and the String concat() method.
Leave a Review