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
  • 20,585
  • 22
  • 95
  • 108
blue-sky
  • 51,962
  • 152
  • 427
  • 752

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,173
  • 2
  • 17
  • 15
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
  • 54,167
  • 9
  • 132
  • 169
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
  • 5,122
  • 8
  • 45
  • 63