Reputation: 12957
Consider the following code example demonstrating the usage of concat() method (Taken from W3Schools Javascript Tutorial):
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript String Methods</h2>
<p>The concat() method joins two or more strings:</p>
<p id="demo"></p>
<script>
var text1 = "Hello";
var text2 = "World!";
var text3 = text1.concat(" ",text2);
document.getElementById("demo").innerHTML = text3;
</script>
</body>
</html>
The output of above program is :
JavaScript String Methods
The concat() method joins two or more strings:
Hello World!
Now, if I want to concat the two words "Hello" and "World!" with a blank space added in between them I can make add a space at the end of the word "Hello " or at the beginning of the word " World!".
If above is the case then how should I do it using the concat() method? Do I still need to provide a blank space as first parameter in concat() method? Please explain me "What is the actual purpose of first parameter in concat method"? Also, explain me it is necessary?
Thanks.
Upvotes: 0
Views: 123
Reputation: 246
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/concat
please refer above link, it has expained multiple cases.
hope it will give answer.
here are multiple way you can concat sting in java-script https://sraji.wordpress.com/2011/01/10/multiple-ways-to-concatenate-a-string-in-javascript/
Upvotes: 0
Reputation: 831
This is useful when the second string (text2) is coming from a variable. For example out of a database, ajaxcalls, everything where you don't control it's content, so it's much cleaner and more readable doing it this way. Also maybe you could have a loop that generates a couple of codes with a "-" as seperator, it much easier to generate them this way.
It's just a way of working you could also use more parameters in the concat function.
Upvotes: 0
Reputation: 853
concat is not a global function, it is available either in array's instance or in string's instance.
In your case, you can use following code :-
String.prototype.concat("Hello ","World")
Here you are accessing concat function directly from the string's prototype
You can also use:-"Hello ".concat("World")
// replace strings with variable if you want text1.concat(text2)
Upvotes: 0
Reputation: 2877
String.concat(str1, str2, str3, ...., strN)
is accepting N number of parameter. This means it will glue all your parameters to one single string.
Upvotes: 1
Reputation: 2152
String.prototype.concat
is a variadic function.
A variadic function takes a variable number of arguments.
In this case, the parameters are of type String
, and are concatenated in the same order they appear.
NOTE: For JavaScript documentation, I strongly recommend Mozilla Developer Network to W3Schools.
Upvotes: 0