How to replace \n with
in JavaScript?

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

    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: '
    \nOne
    \nTwo
    \n
    \nThree
    \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') ? '' : '
    '; return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2'); }

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

提交回复
热议问题