最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - Preserving new lines and spaces in text area not working - Stack Overflow

matteradmin7PV0评论

I am using text area to enter text and on form submit, the text displayed in the view is not retaining any line breaks and spaces.

Text area:

<textarea type="text" id="topicDetails"></textarea>

Tried replacing text using the following:

postTopic(){
    var content = document.getElementById('topicDetails').value;
//            textcontent = content.replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ "" +'$2'); 
//            textcontent = content.replace("\r\n", "\\r\\n"); 
//            textcontent = content.replace(/\r?\n/g, '<br />');
//            textcontent = content.replace(/\r?\n/g, '&#13');
//            var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
//            textcontent = (content + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
    textcontent = content.replace(/\n/g,"<br>")

    var topic = {
        "topicId" : new Date().getTime(),
        "title": document.getElementById('title').value,
        "details": textcontent,
        "username": DataMixin.data.username,
        "userImage": "assets/img/Logos Divine Light/6.png",
        "dayPosted": new Date().toLocaleString()
    }

    console.log('posting blog..... ', topic);
    self.data.blogTopicsArr.push(topic);

    $.ajax({
        url: "/new_topic",
        type: "POST",
        data: JSON.stringify(self.data.blogTopicsArr),
        contentType: "application/json",
        success: function (res) {
            console.log('res is ', res);
            if (res == 'Authentication failed'){
                self.data.blogTopicsArr.splice( - 1, 1);
                self.update(self.data.blogTopicsArr);
                riot.route("signup_popup");
            } else if (res == 'saved'){
                console.log('blog posted successfully: ', self.data.blogTopicsArr);
                document.getElementById('title').value = '';
                document.getElementById('topicDetails').value = '';
                self.update();
            } else if (typeof res.redirect == 'string'){
                console.log('res.redirect ', res.redirect);
                riot.route(res.redirect)
            }
        },
        error: function (err) {
        console.log('err>>>>', err);
        }
    });
    $('#myModal').modal('hide');
}

Tried three different ways with no luck.

The third approach gives the output with <br /> tags. How do I preserve new lines?

Output is:

Lorem Ipsum is simply dummy text.<br /> Industry's standard text ever since the 1500s, <br /><br />Why do we use it?<br />It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. <br /><br />

Update:

After successful form post, I am updating the view using riot's self.update(); or this.update()

Update2

Actually I am sending the form data to database and fetching the text back from database to render it. But the text sent to DB has <br> tag inserted before saving it in DB so why it displays text as Lorem Ipsum is simply dummy text.<br /> Industry's standard text ever since the 1500s, <br /> ??

I am using text area to enter text and on form submit, the text displayed in the view is not retaining any line breaks and spaces.

Text area:

<textarea type="text" id="topicDetails"></textarea>

Tried replacing text using the following:

postTopic(){
    var content = document.getElementById('topicDetails').value;
//            textcontent = content.replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ "" +'$2'); 
//            textcontent = content.replace("\r\n", "\\r\\n"); 
//            textcontent = content.replace(/\r?\n/g, '<br />');
//            textcontent = content.replace(/\r?\n/g, '&#13');
//            var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
//            textcontent = (content + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
    textcontent = content.replace(/\n/g,"<br>")

    var topic = {
        "topicId" : new Date().getTime(),
        "title": document.getElementById('title').value,
        "details": textcontent,
        "username": DataMixin.data.username,
        "userImage": "assets/img/Logos Divine Light/6.png",
        "dayPosted": new Date().toLocaleString()
    }

    console.log('posting blog..... ', topic);
    self.data.blogTopicsArr.push(topic);

    $.ajax({
        url: "/new_topic",
        type: "POST",
        data: JSON.stringify(self.data.blogTopicsArr),
        contentType: "application/json",
        success: function (res) {
            console.log('res is ', res);
            if (res == 'Authentication failed'){
                self.data.blogTopicsArr.splice( - 1, 1);
                self.update(self.data.blogTopicsArr);
                riot.route("signup_popup");
            } else if (res == 'saved'){
                console.log('blog posted successfully: ', self.data.blogTopicsArr);
                document.getElementById('title').value = '';
                document.getElementById('topicDetails').value = '';
                self.update();
            } else if (typeof res.redirect == 'string'){
                console.log('res.redirect ', res.redirect);
                riot.route(res.redirect)
            }
        },
        error: function (err) {
        console.log('err>>>>', err);
        }
    });
    $('#myModal').modal('hide');
}

Tried three different ways with no luck.

The third approach gives the output with <br /> tags. How do I preserve new lines?

Output is:

Lorem Ipsum is simply dummy text.<br /> Industry's standard text ever since the 1500s, <br /><br />Why do we use it?<br />It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. <br /><br />

Update:

After successful form post, I am updating the view using riot's self.update(); or this.update()

Update2

Actually I am sending the form data to database and fetching the text back from database to render it. But the text sent to DB has <br> tag inserted before saving it in DB so why it displays text as Lorem Ipsum is simply dummy text.<br /> Industry's standard text ever since the 1500s, <br /> ??

Share Improve this question edited Feb 7, 2017 at 16:14 kittu asked Feb 7, 2017 at 15:36 kittukittu 7,02821 gold badges103 silver badges199 bronze badges 16
  • Tell us please what you want to achieve? – Zakaria Acharki Commented Feb 7, 2017 at 15:37
  • @ZakariaAcharki As mentioned in title, I want to preserve new lines and white spaces inside text. I am using textarea to enter text and on submit, the white space or new lines are not preserved – kittu Commented Feb 7, 2017 at 15:39
  • @ÁlvaroGonzález I am just posting a form to server. I am using riotjs. I am guessing if this is riotjs issue? – kittu Commented Feb 7, 2017 at 15:55
  • silly question but did you try: postTopic(){ var content = document.getElementById('topicDetails').value; var topic = { "details": content , } } – Chris Lamothe Commented Feb 7, 2017 at 15:58
  • 1 @ÁlvaroGonzález Ok I am updating the question now with more code so you will get an idea. I am just updating the view after form post – kittu Commented Feb 7, 2017 at 16:04
 |  Show 11 more ments

4 Answers 4

Reset to default 4

Actually I all had to was add pre-wrap like below.

<p style="white-space: pre-wrap;">{data.post_details.details}</p>

This retained the spacing with new lines as well.

You can just replace the newlines with <br> using this .replace(/\n/g,"<br>")

function postTopic() {
  var content = document.getElementById('topicDetails').value;

  var textcontent = content.replace(/\n/g,"<br>");

  var topic = {
    "details": textcontent,
  }
}

You want to use

&#10; as \r and

&#13; as \n

Plug those values into your replace function and it should work.

More info:

You could simply handle this when you process the form on the server side. For instance, if your form action is set to "panyForm.php" then in your panyForm.php you could use a function like nl2br, such as:

$panyName = nl2br($_POST['panyName']);

http://php/manual/en/function.nl2br.php

If for whatever reason you absolutely must do this on the client side, you could use nl2br on php.js by adding this:

function nl2br (str, is_xhtml) {

    if (typeof str === 'undefined' || str === null) {
        return ''
    }

    var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
    return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
}

Then use:

nl2br(textcontent, false)
Post a comment

comment list (0)

  1. No comments so far