CamilleClc
CamilleClc

Reputation: 75

Render line breaks entered in textarea

On my website, I create a page where users can write into a textarea. The content of the textarea is then stored into my SQL SERVER database. On an another page, I display all the news that are in the database.

So far, I didn't take into account the CRLF character. So, if users enter a text with line break, the text will be displayed on one line.

Exemple, user enter

Hello

I'm Bob

The result will be :

Hello I'm Bob

I tried by using the replace() function when I display the text into the vue component content.replace(/([^\r]|^)\n/g, "$1\r\n");, but it steel display the text on one line.

I also tried by replacing /([^\r]|^)\n/g by CHAR(13) into the database, but I get the same result.

There is below, sample of my code.

index.html

<html>
  <head>
    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css" href="admin.css">
  </head>
  <body>
      <div class="list">
        <info-generale
          v-for="post in posts"
          v-bind:post="post"
        ></info-generale>
      </div>

      <form class="newPost" action="/newPost" method="POST">
        <textarea id="contentInput" name="contentInput" cols="40" rows="5" required></textarea>
        <button type="submit">Submit</button>
      </form>

    <script src="../js/vue.js"></script>
    <script src="../js/vue-resource.min.js"></script>
    <script type="text/javascript" src="admin.js"></script>
  </body>
</html>

admin.js

Vue.component('info-generale', {
  props: ['post'],
  methods: {
    display: function(content) {
      return content.replace(/([^\r]|^)\n/g, "$1\r\n");
    }
  },
  template: '<div id="infoList"><div id="title"><h4>{{ post.title }}</h4></div><div id="actions">&times;</div><p>{{ display(post.content) }}</p></div>'
})

app.js

server.app.post("/newPost", function(req, res) {
    try {
        dao.newPost(req.body.contentInput).then(value => {
                res.redirect('/');
        })
    } catch (e) {
        console.log(e);
    }
})

DAO.js

async newPost(title, content) {
        try {
            await sql.query('INSERT INTO PROFACE.dbo.Posts (title, content) VALUES (\'' + title.replace(/'/gi,"''")+ '\', \''+content.replace(/'/gi,"''")+'\')').then(value => {
                return true;
            });
        } catch (e) {
            console.log(e);
            return false;
        }
    }

Upvotes: 2

Views: 1336

Answers (1)

BroiSatse
BroiSatse

Reputation: 44715

HTML by default ignores almost all white space characters. You need to wrap your content in <pre> tag or change the wrapping p element style to contain white-space: pre.

Upvotes: 3

Related Questions