Website Development Online Courses

Different ways to concatenate a string in javascript

Hi Friends,

Concatenate a string in three different ways in JavaScript.

Below are the methods

  1. The addition operator (+).
  2. The assignment operator (+=).
  3. The built-in concat method.

Each example is given below

Using addition operator

<script type="text/javascript">
  var str1 = "Hello";
  var str2 = "world";
  var result = str1 + " " + str2;
  document.write(result);
</script>

Using the assignment operator (+=)

<script type = "text/javascript">
  var str1 = "Hello";
  str1 += " world";
  document.write(str1);
</script>

Using the ‘ concat ‘ method

<script type="text/javascript">
  var str1 = "".concat("Hello ","world");
  document.write(str1);
</script>

However multiple ways exist, the addition operator ( + ) is widely used one.

Leave a Reply

Your email address will not be published. Required fields are marked *

nstinftotech.com Copyright © 2017