0

Is there a way to concatenate strings and variable values and new lines, in javascript?

My code:

var variab = "Make:"+ make \n 
        "Model:" + model  \n 
        "Date taken: " + dateTime  \n 
        "File name:" + fileName ;
variab = variab.replace(/\n/g, '<br>');
        document.getElementById('exifid').innerHTML = variab;});

make, model, dateTime and fileName are all variables that return specific values, and I want them to be displayed into a list-like form in my div.

5 Answers 5

3

You almost got it:

var variab = "Make:" + make + "\n" +
    "Model:" + model + "\n" +
    "Date taken: " + dateTime + "\n" +
    "File name:" + fileName ;

variab = variab.replace(/\n/g, '<br>');
document.getElementById('exifid').innerHTML = variab;

You can also put each line in an Array and use .join("<br>") to save yourself some typing.

Sign up to request clarification or add additional context in comments.

Comments

1

Why use the replace?

var variab = "Make:"+ make + "<br>" +
"Model:" + model  + "<br>" +
"Date taken: " + dateTime  + "<br>" +
"File name:" + fileName ;
document.getElementById('exifid').innerHTML = variab;

1 Comment

thanks! i didn't know I could do that, I've just started playing around with js. :)
1

You could stuff each element into an array and then join them.

var array = [
    "Make:"+ make,
    "Model:" + model,
    "Date taken: " + dateTime,
    "File name:" + fileName
];
document.getElementById('exifid').innerHTML = array.join('<br/>');

Comments

1

For greater readability, I'd do this:

var variab = [
    "Make:" + make,
    "Model:" + model, 
    "Date taken: " + dateTime,
    "File name:" + fileName
].join("<br />");

You're also free to include newlines within your fields this way.

Unless your needs grow more complex. In that case, I'd use a templating framework.

Comments

0

It is much, much better to abstract the data into a readable form using a JavaScript object, like below, if possible.

var variab = {
    "Make": "Audi",
    "Model": "A3",
    "Date Taken": 2006,
    "File Name": "audia3.doc"
}

var string = "";

for (var detail_type in variab){
    var detail_data = variab[detail_type];
    string += detail_type + ": " + detail_data + "<br/>"
}

document.getElementById('exifid').innerHTML = variab;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.