Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript - Creating New Lines in a string using "\n"

I've got a string which contains a body of markdown content to be rendered by the ngx-markdown service on Angular 6. The string is stored in a Google Firestore database. So I'm intending to use the "\n" characters to break down the content into individual lines before it is processed by the ngx markdown service.

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

How can I manually replace the "\n" characters in the string with new lines? I have previously used Environment.NewLine() in C# and VB.NET to do the job - does TypeScript have an equivalent method?

like image 539
asimplecore Avatar asked Sep 07 '18 10:09

asimplecore


People also ask

Does \n make a new line?

The newline character ( \n ) is called an escape sequence, and it forces the cursor to change its position to the beginning of the next line on the screen. This results in a new line.

How do I add a new line to a string in typescript?

In typescript use '\n' to add new line.

Does \n work in JavaScript?

The newline character is \n in JavaScript and many other languages. All you need to do is add \n character whenever you require a line break to add a new line to a string.

Why does \n not work in JavaScript?

Your question is not clear but if you mean why "\n" is not visible as text in js then it is because it is newline character i.e it can be used to get an similar effect as html <br> tag.


2 Answers

You need to convert the string by replacing all the \n with <br> tags. And then you need to bind it as HTML instead of string.

Example:

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

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

Now in your template instead of doing this:

<div>{{str}}</div

You need to do this

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

By binding it to innerHTML, you are treating your string as html. Hence the br tags will be processed.

Hope this helps.

like image 125
Vinod Bhavnani Avatar answered Nov 15 '22 10:11

Vinod Bhavnani


I think a better solution to this issue is to put a simple CSS attribute in like:

.content { white-space: pre-line; }
like image 37
Ali Nejad Avatar answered Nov 15 '22 12:11

Ali Nejad