【问题标题】:Javascript str.split at colon char and add line breakJavascript string.split 在冒号字符处并添加换行符
【发布时间】:2020-05-14 12:19:46
【问题描述】:

我觉得这里有点笨。我正在尝试在这样的字符串中的冒号后添加换行符:

LOCATION: SOME OTHER WORDS AFTER

我希望它变成

LOCATION:
SOME OTHER WORDS AFTER 

我的方法是从 Vue 循环中调用的,是这样的:

handleName(name) {
  if (name.includes(":")) {
    return name.replace(":", ":\n");
  } else {
    return name;
  }
}

// the above simply adds a line in the name var but does not actually render an HTML <br>
// I tried using name.split(':'), but for some reason it splits the sting by individual letters.

也许是因为它是像 {{ handleName(location.name) }} 这样从 Vue 调用的,所以我必须以不同的方式处理它?

【问题讨论】:

  • 使用&lt;br /&gt; 代替\n?
  • 所以将其替换为 HTML &lt;br&gt; 而不是 \n
  • 它是这样渲染的,因为您使用的任何框架都在转义/编码 HTML 标记。您需要提供更多上下文并相应地标记您的问题。
  • 使用v-html 指令。
  • @RobbyCornelissen 就是这样,谢谢先生。如果你愿意,把它放在一个答案中,我会接受它,这样你就可以获得名声、荣耀和财富。

标签: javascript string vue.js


【解决方案1】:

你应该使用&lt;br/&gt;标签而不是\n

handleName(name) {
  if (name.includes(":")) {
    return name.replace(":", ":<br/>");
  } else {
    return name;
  }
}

Vue.JS 中的示例,使用v-html 指令将字符串显示为标记:

<template>
    <span v-html="message"></span>
</template>

<script>
export default {
  name: "App",
  data(){
    return {
      message: "LOCATION: SOME OTHER WORDS AFTER".replace(":",":<br/>")
    }    
  },
};
</script>

【讨论】:

    【解决方案2】:

    你需要:

    1. 确保插入 HTML 换行符 (&lt;br&gt;) 而不是换行符 (\n)。除了&lt;pre&gt; 等特定标签内,HTML 默认折叠空白,换行不会呈现为新行。

    2. 确保将替换操作的结果作为 HTML 而不是文本传递给渲染器。如果作为文本传递,渲染器会将&lt;br&gt; 标记中的小于(&amp;lt;)和大于(&amp;gt;)符号替换为其等效实体(&amp;lt;&amp;gt;)。

    在 VueJS 中,您可以为此使用 v-html 指令:

    <span v-html="name.replace(/:\s*/g, '<br>')"></span>
    

    (!) 将用户定义的内容输出为原始 HTML 时要小心。您可能会对 XSS(及相关)漏洞敞开心扉。

    【讨论】:

      【解决方案3】:

      以下演示具有一个函数,该函数将在给定字符串的冒号后断开文本。此函数将在 HTML 中呈现文本或将编辑后的文本作为字符串值返回以在其他地方使用。

      /** 
       * colonBreak(data, DOM = false)
       =------------------------------=
       * Edit text in a particular format pattern:
       *   Insert a line break after any colon.
       =------------------------------------------=
       * @param {string} data - There are two forms of strings that can be accepted:
       *                        1. a literal string or template literal 
       *                        2. the selector of a DOM element that has the text 
       * @param {boolean} DOM - If undefined it defaults to false 
       *                        true:  data represents the selector of a DOM element
       *                               text of DOM element will be formatted
       *                        false: data is the string to be formatted
       =----------------------------------------------------------------------------=
       * @return {string}       if DOM is false, a formatted string will be returned. 
       *            or 
       *         {undefined}    if DOM is true, undefined will be returned and the DOM 
       *                        element text content will be formatted
       */ 
      

      说明

      在处理 DOM 元素的文本时,HTML 默认格式化文本,以便规范化多个空格和换行符。使用.innerText 属性以便保留空格和换行符(\n 不会被忽略)。 .innerText.textContent 可用于提取文本,但重要的是应用 .innerText 将格式化的字符串呈现回 DOM 元素。

      string = node.innerText;
      

      这个函数的核心是 .split() 方法,它通过 RegExp 分隔符将字符串拆分为字符串数组:

      string.split(/([\w]+:)\s*/)...
      

      RegExp 分隔符说明如下:

      1. (...) 捕获括号内的匹配项并将其用作替换
      2. [...] 匹配每个字符和/或元字符的文字和/或类
      3. \w 匹配任何字母数字字符(包括下划线)的元字符
      4. + 量词表示 一个 或多个 匹配的连续实例之前的匹配
      5. : 文字冒号
      6. \s 匹配空格的元字符
      7. * 量词为 + 但匹配 或更多

      最后使用的方法是.join(),它将通过给定的分隔符将数组的所有字符串连接成一个完整的字符串:

      let formatted = string.split(/([\w]+:)\s*/).join('\n')
      

      演示

      详情在demo中注释

      /* 
      There are two examples of input:
        1. A <p> with text (located in HTML window of demo)
        2. A string assigned to the variable dataString (below)
          (NOTE: colonBreak() normalizes spacing as well)
      */
      const dataString = `keyX: xXxXxXXxXxXx keyY:yYyYyY YyYyYy keyZ: zZ zZ zZ Zz Zz Zz`;
      
      /* 
      See documentation in post about the parameters and return
      */
      function colonBreak(data, DOM = false) {
        let node, string;
      
        // if DOM parameter is true...
        if (DOM) {
          /*
          - Reference the DOM element designated by param data
          - Get the textNode within the DOM element
            (NOTE: .innerText preserves whitespaces)
          - Overwrite textNode with the formatted text
            (NOTE: See post on how text is formatted)
          */
          node = document.querySelector(data);
          string = node.textContent;
          node.innerText = string.split(/([\w]+:)\s*/).join(`\n`);
        } else {
          /*
          ...otherwise just return the formatted text
          (NOTE: See post on how text is formatted)
          */
          return data.split(/([\w]+:)\s*/).join(`\n`);
        }
        return false;
      }
      
      console.log(colonBreak(dataString));
      colonBreak('p', true);
      .as-console-wrapper {
        width: 350px;
        min-height: 100%;
        margin-left: 45%;
      }
      &lt;p&gt;keyX: xXxXxXXxXxXx keyY:yYyYyY YyYyYy keyZ: zZ zZ zZ Zz Zz Zz&lt;/p&gt;

      【讨论】:

        【解决方案4】:

        \n 这样的普通换行符在html 中呈现为空白。要实际呈现换行符,您可以使用 &lt;br&gt; 元素。此外,您不需要检查字符串中是否存在冒号。即使它不存在,您也可以安全地尝试替换它。

        handleName(name) {
            return name.replace(":", ":<br/>");
        }
        

        【讨论】:

          【解决方案5】:

          为了避免混淆。可以在字符串中使用\nspan 或其他任何东西。

          但是,如果您将其分配给innerText,这将有效。如果您或您正在使用的任何东西使用innerHTML,它将无法按预期工作(参见示例)。

          function handleName(string) {
            return string.replace(":", ":\n");
          }
          
          let div = document.getElementById('div');
          let div2 = document.getElementById('div2')
          let name = handleName(div.innerText);
          div.innerText = name;
          div2.innerHTML = name;
          div{
            margin-bottom: 10px;
          }
          <div id='div'>LOCATION: SOME OTHER WORDS AFTER</div>
          <div id='div2'></div>

          【讨论】:

            猜你喜欢
            • 2013-04-02
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2022-01-06
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多