2

I have multiple strings as below -

var str1 = "this is a test that goes on and on"+param1
var str2 = "this is also a test this is also"+param2+" a test this is also a test this is also a tes" 
var str3 = "this is also a test"

I'm assigning each string into its own var so as to keep the code readable and prevent the string values from trailing across the string. Also as I have read that the newline javascript character does not work in all browsers - Creating multiline strings in JavaScript

I then concat the strings -

var concatStr = str1 + str2 + str3

and return the string concatenated value.

Is this an acceptable method of breaking up a large string into into its parts. Or can it be improved ?

Stephen Kennedy
  • 18,869
  • 22
  • 90
  • 106
blue-sky
  • 49,326
  • 140
  • 393
  • 691

3 Answers3

6

There's no need to assign each line to a different variable:

var str1 = "this is a test that goes on and on"+param1 +
     "this is also a test this is also"+param2+
     " a test this is also a test this is also a tes" +
     "this is also a test";

Personally, I'd do the following:

var string = ['hello ', param1,
              'some other very long string',
              'and another.'].join(''); 

For me, it's easier to type out, and read.

osahyoun
  • 5,057
  • 2
  • 16
  • 14
1

If you use really long string, then hold parts of it in an array and then join them:

ARRAY = ['I', 'am', 'joining', 'the', 'array', '!'];
ARRAY.join(' ');

and the result:

"I am joining the array !"

Keep in mind, that if you need to do this in Client-Side JavaScript, then probably you'r doing something wrong. :)

freakish
  • 51,131
  • 8
  • 123
  • 162
0

You can use an array. Its join method is fastest way to concatenate strings.

var myArray = [
   "this is a test that goes on and on"+param1,
   "this is also a test this is also"+param2+" a test this is also a test this is also a tes",
   "this is also a test"
];

and then use:

myArray.join('');

to get your complete string.

wasimbhalli
  • 4,798
  • 8
  • 42
  • 61