简体   繁体   English

Javascript str.split 在冒号字符处并添加换行符

[英]Javascript str.split at colon char and add line break

I feel a bit dumb here.我觉得这里有点傻。 I'm trying to add a line break after a colon in a string like this:我正在尝试在这样的字符串中的冒号后添加换行符:

LOCATION: SOME OTHER WORDS AFTER

I would like it to become我希望它成为

LOCATION:
SOME OTHER WORDS AFTER 

My method, being called from a Vue loop, is this:我的方法是从 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.

Maybe because it's being called from Vue like {{ handleName(location.name) }} I have to handle it differently?也许是因为它是像{{ handleName(location.name) }}这样从 Vue 调用的,所以我必须以不同的方式处理它?

You should use the <br/> tag instead of \n :您应该使用<br/>标签而不是\n

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

Example in Vue.JS, using the v-html directive to display String as markup: 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>

You need to:你需要:

  1. Make sure that you insert an HTML linebreak ( <br> ) instead of a newline character ( \n ).确保插入 HTML 换行符 ( <br> ) 而不是换行符 ( \n )。 Except inside specific tags like <pre> , HTML collapses white-space by default, and the newline will not be rendered as a new line.除了像<pre>这样的特定标签之外,HTML 默认会折叠空白,并且换行符不会呈现为新行。

  2. Make sure that you pass the result of the replace operation to the renderer as HTML, and not as text.确保将替换操作的结果作为 HTML 而不是文本传递给渲染器。 If passed as text, the renderer will replace the less than ( < ) and greater than ( > ) symbols in the <br> tags with their equivalent entities ( &lt; and &gt; ).如果作为文本传递,渲染器会将<br>标记中的小于 ( < ) 和大于 ( > ) 符号替换为其等效实体 ( &lt;&gt; )。

In VueJS, you can use the v-html directive for this:在 VueJS 中,您可以为此使用v-html指令:

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

(!) Be careful when outputting user-defined content as raw HTML. (!) 将用户定义的内容输出为原始 HTML 时要小心。 You might be opening yourself up to XSS (and related) vulnerabilities.您可能会对 XSS(和相关)漏洞敞开心扉。

Normal line breakes like \n are rendered as a white space in an html.\n这样的普通换行符在 html 中呈现为空白。 To actually render a line break, you can use a <br> element.要实际呈现换行符,您可以使用<br>元素。 Also you don't need to check if the colon exists in the string.此外,您不需要检查字符串中是否存在冒号。 You can safely attempt to replace it even if it doesn't exist.即使它不存在,您也可以安全地尝试替换它。

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

To avoid any confusion.为了避免任何混淆。 It is fine to use a \n in a string, span or whatever.可以在字符串、 span或其他任何内容中使用\n

BUT this works if you assign it to innerText .但是,如果您将其分配给innerText ,则此方法有效。 If you or whatever you are using uses innerHTML it won't work as expected (see example).如果您或您正在使用的任何东西使用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>

The following demo features a function that will break text after a colon on a given string.以下演示具有一个函数,该函数将在给定字符串的冒号后断开文本。 This function will render the text in HTML or return the edited text as a string value to used elsewhere.此函数将以 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
 */ 

Explanation解释

When dealing with the text of DOM elements, HTML formats text by default so that multiple whitespaces and line-breaks are normalized.在处理 DOM 元素的文本时,HTML 默认格式化文本,以便规范化多个空格和换行符。 .innerText property is used so that the whitespaces and line-breaks are preserved ( \n is not ignored).使用.innerText属性以便保留空格和换行符( \n不会被忽略)。 .innerText or .textContent can be used to extract the text but it's important to apply .innerText to render the formatted string back into the DOM element. .innerText.textContent可用于提取文本,但重要的是应用.innerText将格式化的字符串呈现回 DOM 元素。

string = node.innerText;

The heart of this function consists of .split() method witch splits the string by a RegExp delimiter into an array of strings:该函数的核心由.split()方法组成,该方法通过 RegExp 分隔符将字符串拆分为字符串数组:

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

The RegExp delimiter instructions are as follows: RegExp 分隔符说明如下:

  1. ( ... ) capture the match within the parenthesis and use it as a replacement ( ... )捕获括号内的匹配项并将其用作替换
  2. [ ... ] match the literal and/or class of each character and/or meta-character [ ... ]匹配每个字符和/或元字符的文字和/或类
  3. \w meta-character that matches any alphanumeric character (including underscores) \w匹配任何字母数字字符(包括下划线)的元字符
  4. + quantifier indicating match of one or more consecutive instances of the match preceding it +量词,表示匹配它之前的一个或多个连续实例
  5. : literal colon :文字冒号
  6. \s meta-character that matches a whitespace \s匹配空格的元字符
  7. * quantifier as + but matches zero or more *量词为+但匹配个或多个

Last method used is .join() which will join all the strings of an array into one complete string by a given delimiter:最后使用的方法是.join() ,它将通过给定的分隔符将数组的所有字符串连接成一个完整的字符串:

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

Demo演示

Details are commented in demo细节在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%; }
 <p>keyX: xXxXxXXxXxXx keyY:yYyYyY YyYyYy keyZ: zZ zZ zZ Zz Zz Zz</p>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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