简体   繁体   中英

String concatenation in Javascript

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.

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.

Why use the replace?

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

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.

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/>');

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM