在 JavaScript 中使用“if”语句连接字符串

发布于 2024-12-03 21:56:25 字数 866 浏览 5 评论 0原文

我正在尝试设置一个脚本来连接字符串中的一些变量如果它们存在,以便将适当的元数据标记放入渲染的 HTML 文档中。

我的串联代码是:

data = "<html>\n<head>\n" + "</head>\n<body>\n\n" + paras.join("\n\n") + "\n\n</body>\n</html>";

我正在尝试添加如下所示的 if 语句(在第一项和第二项之间):

if (typeof metadata_title !== "undefined") {
    "<title>" + metadata_title + "</title>\n"
}
if (typeof metadata_author !== "undefined") {
    "<meta name=\"author\" content=\"" + metadata_author + "\"></meta>\n"
}
if (typeof metadata_date !== "undefined") {
    "<meta name=\"date\" content=\"" + metadata_date + "\"></meta>\n"
}

但我无法将这些语句中的任何一个直接添加到串联代码中 (它抛出一个错误:意外的标记()。

我如何最好地将此类语句添加到我的串联字符串中?

I'm attempting to set up a script to concatenate some variables inside a string if they exist, in order to place the appropriate metadata tags into a rendered HTML document.

My concatenation code is:

data = "<html>\n<head>\n" + "</head>\n<body>\n\n" + paras.join("\n\n") + "\n\n</body>\n</html>";

I'm trying to add if statements like the following into it (between the first and second items):

if (typeof metadata_title !== "undefined") {
    "<title>" + metadata_title + "</title>\n"
}
if (typeof metadata_author !== "undefined") {
    "<meta name=\"author\" content=\"" + metadata_author + "\"></meta>\n"
}
if (typeof metadata_date !== "undefined") {
    "<meta name=\"date\" content=\"" + metadata_date + "\"></meta>\n"
}

But I can't add any of these statements directly into the concatenation code
(it throws an error: Unexpected token ().

How best would I go about adding statements such as these into my concatenation string?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

原野 2024-12-10 21:56:25

我会使用三元运算符

data = "<html>\n"
     + "<head>\n" 
     + ( typeof metadata_title  !== "undefined" ?  "<title>" + metadata_title + "</title>\n"                             : "" )
     + ( typeof metadata_author !== "undefined" ?  "<meta name=\"author\" content=\"" + metadata_author + "\"></meta>\n" : "" )
     + ( typeof metadata_date   !== "undefined" ?  "<meta name=\"date\" content=\"" + metadata_date + "\"></meta>\n"     : "" )
     + "</head>\n"
     + "<body>\n"
     + "\n"
     + paras.join("\n\n")
     + "\n"
     + "\n"
     + "</body>\n"
     + "</html>"
;

I'd use a ternary operator:

data = "<html>\n"
     + "<head>\n" 
     + ( typeof metadata_title  !== "undefined" ?  "<title>" + metadata_title + "</title>\n"                             : "" )
     + ( typeof metadata_author !== "undefined" ?  "<meta name=\"author\" content=\"" + metadata_author + "\"></meta>\n" : "" )
     + ( typeof metadata_date   !== "undefined" ?  "<meta name=\"date\" content=\"" + metadata_date + "\"></meta>\n"     : "" )
     + "</head>\n"
     + "<body>\n"
     + "\n"
     + paras.join("\n\n")
     + "\n"
     + "\n"
     + "</body>\n"
     + "</html>"
;
过期以后 2024-12-10 21:56:25
data = "<html>\n<head>\n" 
    + (
        typeof metadata_title !== "undefined" ?
        "<title>" + metadata_title + "</title>\n" :
        ""
    )
    + (
        typeof metadata_author !== "undefined" ?
        "<meta name=\"author\" content=\"" + metadata_author + "\"></meta>\n" :
        ""
    )
    + (
        typeof metadata_date !== "undefined" ?
         "<meta name=\"date\" content=\"" + metadata_date + "\"></meta>\n" :
        ""
    )
    + "</head>\n<body>\n\n" 
    + paras.join("\n\n") 
    + "\n\n</body>\n</html>";
data = "<html>\n<head>\n" 
    + (
        typeof metadata_title !== "undefined" ?
        "<title>" + metadata_title + "</title>\n" :
        ""
    )
    + (
        typeof metadata_author !== "undefined" ?
        "<meta name=\"author\" content=\"" + metadata_author + "\"></meta>\n" :
        ""
    )
    + (
        typeof metadata_date !== "undefined" ?
         "<meta name=\"date\" content=\"" + metadata_date + "\"></meta>\n" :
        ""
    )
    + "</head>\n<body>\n\n" 
    + paras.join("\n\n") 
    + "\n\n</body>\n</html>";
枉心 2024-12-10 21:56:25

我可能会做一些不同的事情(更类似于模板),主要是因为我讨厌用 Javascript 完成串联 HTML:

var metadata_title = "Hello";
var metadata_author = "Me";
var metadata_date = "2011-09-07";

var template = "<html>\
            <head>\
                <title>#title#</title>\
                <meta name=\"author\" content=\"#author#\"></meta>\
                <meta name=\"date\" content=\"#date#\"></meta>\
            </head>\
            <body>\
            </body>\
            </html>";

var data = template.replace("#title#", metadata_title != undefined ? metadata_title : "")
                   .replace("#author#", metadata_author != undefined ? metadata_author : "")
                   .replace("#date#", metadata_date != undefined ? metadata_date : "");

当然,有非常少量的额外开销,但对我来说,它< em>更具可读性。

I might do something a little different (a little more akin to templating), mainly because I hate concatenated HTML done with Javascript:

var metadata_title = "Hello";
var metadata_author = "Me";
var metadata_date = "2011-09-07";

var template = "<html>\
            <head>\
                <title>#title#</title>\
                <meta name=\"author\" content=\"#author#\"></meta>\
                <meta name=\"date\" content=\"#date#\"></meta>\
            </head>\
            <body>\
            </body>\
            </html>";

var data = template.replace("#title#", metadata_title != undefined ? metadata_title : "")
                   .replace("#author#", metadata_author != undefined ? metadata_author : "")
                   .replace("#date#", metadata_date != undefined ? metadata_date : "");

Sure, there's a very small amount of additional overhead, but to me, it's way more readable.

木落 2024-12-10 21:56:25

将整个文档构建成一个数组,然后在末尾添加 "\n" 。 (这样做的理由当然是不要有大量的新行分散在各处!如果您使用的是 IE7 或更低版本,Array#join 比重复的字符串连接要快得多。)

代码如下: http://jsfiddle.net/ZCbCZ/

更新 我忘记包括“段落”中第一把小提琴。带有段落的代码在这里: http://jsfiddle.net/U8325/1/

对于那些不想点击并尝试一下,这是脚本:

// Not going to define metadata_author just to be saved by typeof :-)
var metadata_title = "Hello";
var metadata_date = "2011-09-07";

// Okay 3 paras for fun
var paras = ["<p>paragraph1</p>", "<p>paragraph2</p>", "<p>paragraph3</p>"];

data = ["<html>", "<head>"]

if (typeof metadata_title !== "undefined") {
    data.push("<title>" + metadata_title + "</title>");
}
if (typeof metadata_author !== "undefined") {
    data.push("<meta name=\"author\" content=\"" + metadata_author + "\"></meta>");
}
if (typeof metadata_date !== "undefined") {
    data.push("<meta name=\"date\" content=\"" + metadata_date + "\"></meta>");
}

data.push("</head>");
data.push("<body>");
paras.forEach(function (p) {data.push(p);});   // Requires ES5; use a for-loop if you don't have it
data.push("</body>");
data.push("<html>");
data = data.join("\n");
alert(data);

Build up the entire document into an array, then join with a "\n" at the end. (The rationale for this is of course to not have lots of new lines scattered all about! And if you are on IE7 or less, Array#join is considerably faster than repeated string concatenation.)

Code here: http://jsfiddle.net/ZCbCZ/

UPDATE I forgot to include the "paras" in the first fiddle. The code with the paras is here: http://jsfiddle.net/U8325/1/

For those not wishing to click through and try it out, here is the script:

// Not going to define metadata_author just to be saved by typeof :-)
var metadata_title = "Hello";
var metadata_date = "2011-09-07";

// Okay 3 paras for fun
var paras = ["<p>paragraph1</p>", "<p>paragraph2</p>", "<p>paragraph3</p>"];

data = ["<html>", "<head>"]

if (typeof metadata_title !== "undefined") {
    data.push("<title>" + metadata_title + "</title>");
}
if (typeof metadata_author !== "undefined") {
    data.push("<meta name=\"author\" content=\"" + metadata_author + "\"></meta>");
}
if (typeof metadata_date !== "undefined") {
    data.push("<meta name=\"date\" content=\"" + metadata_date + "\"></meta>");
}

data.push("</head>");
data.push("<body>");
paras.forEach(function (p) {data.push(p);});   // Requires ES5; use a for-loop if you don't have it
data.push("</body>");
data.push("<html>");
data = data.join("\n");
alert(data);
骄兵必败 2024-12-10 21:56:25

我喜欢 Demian Brecht 答案的可读性,但我只会更改正则表达式的字符串相反,因为 Replace() 函数仅替换第一个匹配项(请参阅此处的更多内容:JavaScript .replace 仅替换第一个匹配

var metadata_title = "Hello";
var metadata_author = "Me";
var metadata_date = "2011-09-07";

var template = "<html>\
            <head>\
                <title>#title#</title>\
                <meta name=\"author\" content=\"#author#\"></meta>\
                <meta name=\"date\" content=\"#date#\"></meta>\
            </head>\
            <body>\
            </body>\
            </html>";

var data = template.replace(/#title#/g, metadata_title != undefined ? metadata_title : "")
                   .replace(/#author#/g, metadata_author != undefined ? metadata_author : "")
                   .replace(/#date#/g, metadata_date != undefined ? metadata_date : "");

I liked the readability of Demian Brecht answer, but I would only change the string for a regex instead, because the replace() function only replaces the first match (see more here: JavaScript .replace only replaces first Match)

var metadata_title = "Hello";
var metadata_author = "Me";
var metadata_date = "2011-09-07";

var template = "<html>\
            <head>\
                <title>#title#</title>\
                <meta name=\"author\" content=\"#author#\"></meta>\
                <meta name=\"date\" content=\"#date#\"></meta>\
            </head>\
            <body>\
            </body>\
            </html>";

var data = template.replace(/#title#/g, metadata_title != undefined ? metadata_title : "")
                   .replace(/#author#/g, metadata_author != undefined ? metadata_author : "")
                   .replace(/#date#/g, metadata_date != undefined ? metadata_date : "");
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文