代码之家  ›  专栏  ›  技术社区  ›  darkhorse

在JavaScript中有条件地向字符串添加关键字

  •  0
  • darkhorse  · 技术社区  · 3 年前

    • "{% if some_condition %}" (开始)
    • "{% endif %}"
    • "{% else if some_other_condition %}" (可选)
    • "{% else %}" (可选)

    除了这些关键字外,输入还可能包含任何其他字符串。这些条件基本上只是变量的名称,因此在解析之前的字符串中,它们只是字符串(任何有效字符串都可以接受为变量名称)。

    下面是函数的作用:

    • 如果内容包含 "{% else if <any_condition> %}" “{%else%}”
    • 否则,请添加 "{% else %}<div class='empty'>Empty</div>" 字符串位于内容的末尾。

    为了清楚起见,这里有一个例子 输入

    {% if username %}
      <p>Hello {{ username }}</p>
    {% endif %}
    
    {% if score > 10 %}
      <p>You are doing great.</p>
    {% else if score > 50 %}
      <p>You are freaking amazing!</p>
    {% endif %}
    
    <p>This is your <strong>awesome</strong> profile page.</p>
    
    {% if not email %}
      <p>Please consider setting your email address</p>
    {% endif %}
    
    {% if balance > 0 %}
      <p>You are ready to go!</p>
    {% else %}
      <p>No balance</p>
    {% endif %}
    

    输出 具体如下:

    {% if username %}
      <p>Hello {{ username }}</p>
    {% else %}<div class="empty">Empty</div>{% endif %}
    
    {% if score > 10 %}
      <p>You are doing great.</p>
    {% else if score > 50 %}
      <p>You are freaking amazing!</p>
    {% endif %}
    
    <p>This is your <strong>awesome</strong> profile page.</p>
    
    {% if not email %}
      <p>Please consider setting your email address</p>
    {% else %}<div class="empty">Empty</div>{% endif %}
    
    {% if balance > 0 %}
      <p>You are ready to go!</p>
    {% else %}
      <p>No balance</p>
    {% endif %}
    

    简而言之,如果 if 块没有条件,则在结束标记之前追加额外的字符串。希望这是有道理的。我知道这要求很高,但有人能让我从正确的方向开始吗?我不太擅长使用JavaScript的正则表达式,它基本上是踢我的屁股。谢谢你的帮助!

    1 回复  |  直到 3 年前
        1
  •  1
  •   Fredo Corleone    3 年前

    我想要以下的。标志“g”是全局的,“m”是多行的,“s”是“dotall”模式,这意味着“.”可以抓取“\n”。我获取所有输入,替换它们,看看是否有“else-if”或“else”,因此将“{%endif%}”替换为“{%else%}”加上您想要的加上“{%endif%}”。

    input.replace(
        /{% if.*?%}.*?{% endif %}/gms,
        match => 
            (!/(else if|else)/.test(match))
                ? match.replace(
                    /{% endif %}/,
                   '{% else %}<div class="empty">Empty</div>{% endif %}'
                  )
                : match
    );
    
    /*{% if username %}
      <p>Hello {{ username }}</p>
    {% else %}<div class="empty">Empty</div>{% endif %}
    
    {% if score > 10 %}
      <p>You are doing great.</p>
    {% else if score > 50 %}
      <p>You are freaking amazing!</p>
    {% endif %}
    
    <p>This is your <strong>awesome</strong> profile page.</p>
    
    {% if not email %}
      <p>Please consider setting your email address</p>
    {% else %}<div class="empty">Empty</div>{% endif %}
    
    {% if balance > 0 %}
      <p>You are ready to go!</p>
    {% else %}
      <p>No balance</p>
    {% endif %}*/