How to replace \n with
in JavaScript?

后端 未结 10 2100
面向向阳花
面向向阳花 2020-12-31 00:44

I have a textarea where I insert \\n when user presses enter. Code from this textarea is sent to a WCF service via jQuery.ajax(). I cannot save

相关标签:
10条回答
  • 2020-12-31 01:08

    The following will replace all instances of \n with a <br /> :

    while (message.indexOf("\\n") !== -1) {
       message = message.replace("\\n", "<br />");
    }
    
    0 讨论(0)
  • 2020-12-31 01:12

    Like said in comments and other answer, it's better to do it on server side.

    However if you want to know how to do it on clientside this is one easy fix:

    textareaContent.replace(/\\n/g, "<br />");
    

    Where textareaContent is the variable with the data in the textarea.

    Edit: Changed so that it replaces globally and not only first match.

    0 讨论(0)
  • 2020-12-31 01:15

    You can use a simple javascript string function.

     string.replace("\n", "<br>")
    
    0 讨论(0)
  • 2020-12-31 01:16

    If you support PHP you should check this out: http://php.net/manual/en/function.nl2br.php

    0 讨论(0)
  • 2020-12-31 01:20

    you can use javascript built in replace function with a little help of regex, for example

    $('#input').val().replace(/\n\r?/g, '<br />')
    

    this code will return all enters replaced with <br>

    0 讨论(0)
  • 2020-12-31 01:21

    Replace with global scope

    $('#input').val().replace(/\n/g, "<br />")
    

    or

    $('#input').val().replace("\n", "<br />", "g")
    
    0 讨论(0)
提交回复
热议问题