How to replace \n with
in JavaScript?

后端 未结 10 2101
面向向阳花
面向向阳花 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:21

    it could be done like this:

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

    edit: sorry ... the regular expressions in javascript should not be quoted

    working example

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

    Building on the other answers, this is probably done best by php. Now assuming you don't want to ajax this (which would be pointless and cause unnecessary server load), you should probably use phpjs.org's javascript port of this function:

    function nl2br (str, is_xhtml) {
        // Converts newlines to HTML line breaks  
        // 
        // version: 1103.1210
        // discuss at: http://phpjs.org/functions/nl2br    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
        // +   improved by: Philip Peterson
        // +   improved by: Onno Marsman
        // +   improved by: Atli Þór
        // +   bugfixed by: Onno Marsman    // +      input by: Brett Zamir (http://brett-zamir.me)
        // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
        // +   improved by: Brett Zamir (http://brett-zamir.me)
        // +   improved by: Maximusya
        // *     example 1: nl2br('Kevin\nvan\nZonneveld');    // *     returns 1: 'Kevin\nvan\nZonneveld'
        // *     example 2: nl2br("\nOne\nTwo\n\nThree\n", false);
        // *     returns 2: '<br>\nOne<br>\nTwo<br>\n<br>\nThree<br>\n'
        // *     example 3: nl2br("\nOne\nTwo\n\nThree\n", true);
        // *     returns 3: '\nOne\nTwo\n\nThree\n'    var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '' : '<br>';
    
        return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
    }
    

    http://phpjs.org/functions/nl2br:480

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

    From within your WCF service can you not just use String.Replace ?

    text = text.Replace("\n","<br />");
    
    0 讨论(0)
  • 2020-12-31 01:26
    var replaced = $('#input').val().replace("\n", "<br/>");
    
    0 讨论(0)
提交回复
热议问题