Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make space between strings using concat() method in JavaScript

I want to concat multiple string using concat() method it works fine but how can i make white space between them

<HTML>
    <head>
       <title></title>
    </head>
    <body>
       <label id="label_one" style="color:blue;"></label><br/>
       <label id="label_two" style="color:blue;"></label><br/>
       <label id="label_three" style="color:blue;"></label><br/>
       <script>
           var one = "abc";
           var two = "def";
           var three = one.concat(two)
           var four = three.length;
           var variableLen = one.concat(three, four);
           document.getElementById("label_one").innerHTML = one;
           document.getElementById("label_two").innerHTML = two;
           document.getElementById("label_three").innerHTML = variableLen;
       </script>
    </body>
</HTML>

and my output is

abcdef6 I want my output like this abc def 6 with space after concate and using concate() method of JavaScript not with concate operator(+)

like image 281
Raheel Avatar asked Jul 14 '26 19:07

Raheel


2 Answers

Try this [one,two].join(' '); (Adapt to your needs as necessary, i.e. build an array of strings, then use join)

like image 197
Jochen Bedersdorfer Avatar answered Jul 18 '26 08:07

Jochen Bedersdorfer


One way of doing it is:

var one = "abc";
var two = "def";
var three = one.concat(" ", two);
var four = three.length;
var variableLen = one.concat(" ", two, " ", four);

However it might be better to use join as another answer mentions. On a side note, you might notice that the concat() function takes a variable number of arguments. You can achieve this in your own functions like this:

function func1() {
  console.log(arguments); // => [1,2,3]
}

func1(1, 2, 3);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments

like image 21
Zach Smith Avatar answered Jul 18 '26 08:07

Zach Smith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!