打字稿-使用“ \ n”在字符串中创建新行

时间:2018-09-07 10:18:07

标签: angular typescript

我有一个字符串,其中包含要由Angular 6上的ngx-markdown服务呈现的markdown内容主体。该字符串存储在Google Firestore数据库中。因此,我打算在ngx markdown服务处理内容之前,使用“ \ n”字符将内容分解为几行。

First ordered list item\n2. Another item\n * Unordered sub-list.\n1. Actual numbers don't matter, just that it's a number\n 1. Ordered sub-list\n4. And another item.\n\n You can have properly indented paragraphs within list items. Notice the blank line above, and the leading spaces (at least one, but we'll use three here to also align the raw Markdown).\n\n To have a line break without a paragraph, you will need to use two trailing spaces. \n Note that this line is separate, but within the same paragraph. \n (This is contrary to the typical GFM line break behaviour, where trailing spaces are not required.)\n\n\n* Unordered list can use asterisks\n- Or minuses\n+ Or pluses

如何用新行手动替换字符串中的“ \ n”字符?我以前在C#和VB.NET中使用Environment.NewLine()来完成这项工作-TypeScript是否具有等效的方法?

2 个答案:

答案 0 :(得分:3)

您需要通过将所有\n替换为<br>标签来转换字符串。然后,您需要将其绑定为HTML而不是字符串。

示例:

str: String = "First ordered list item\n2. Another item\n * Unordered sub-list.\n"

//Replace \n with <br>
this.str.replace("\n", "<br>");

现在在模板中,而不要这样做:

<div>{{str}}</div

您需要这样做

<div [innerHTML]="str"></div>

通过将其绑定到innerHTML,您会将字符串视为html。因此,将处理br标签。

希望这会有所帮助。

答案 1 :(得分:2)

\n输入到innerText属性中时,它们被视为新行。

看:

const div = [...document.querySelectorAll('div')];

div[0].innerHTML = 'New\nLine';
div[1].innerText = 'New\nLine';

const txt = document.createTextNode("New\nLine");
div[2].appendChild(txt);
div {
  border: 1px solid #ddd;
  margin: 12px 0;
  padding: 12px;
}
<div></div>
<div></div>
<div></div>

接下来,您可以将字符串分成一个数组,并显示块元素:

const str = `First ordered list item\n2. Another item\n * Unordered sub-list.\n1. Actual numbers don't matter, just that it's a number\n 1. Ordered sub-list\n4. And another item.\n\n You can have properly indented paragraphs within list items. Notice the blank line above, and the leading spaces (at least one, but we'll use three here to also align the raw Markdown).\n\n To have a line break without a paragraph, you will need to use two trailing spaces. \n Note that this line is separate, but within the same paragraph. \n (This is contrary to the typical GFM line break behaviour, where trailing spaces are not required.)\n\n\n* Unordered list can use asterisks\n- Or minuses\n+ Or pluses`;

const arr = str.split('\n');

arr.forEach(item => {
  const div = document.createElement('div');
  div.innerText = item;
  document.body.appendChild(div);
});