blue-sky
blue-sky

Reputation: 53806

Breaking up a large string into parts

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 ?

Upvotes: 2

Views: 1532

Answers (3)

osahyoun
osahyoun

Reputation: 5231

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.

Upvotes: 6

wasimbhalli
wasimbhalli

Reputation: 5242

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.

Upvotes: 0

freakish
freakish

Reputation: 56467

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. :)

Upvotes: 1

Related Questions