How replace HTML
with newline character “\n”

后端 未结 3 1957
栀梦
栀梦 2020-12-16 09:57

How can I replace HTML

or
with new line character \"\\n\"

相关标签:
3条回答
  • 2020-12-16 10:48

    This function considers whether to remove or replace the tags such as <br>, <BR>, <br />, </br>.

    /**
     * This function inverses text from PHP's nl2br() with default parameters.
     *
     * @param {string} str Input text
     * @param {boolean} replaceMode Use replace instead of insert
     * @return {string} Filtered text
     */
    function br2nl (str, replaceMode) {   
    
      var replaceStr = (replaceMode) ? "\n" : '';
      // Includes <br>, <BR>, <br />, </br>
      return str.replace(/<\s*\/?br\s*[\/]?>/gi, replaceStr);
    }
    

    In your case, you need to use replaceMode. For eaxmple: br2nl('1st<br>2st', true)

    Demo - JSFiddle

    JavaScript nl2br & br2nl functions

    0 讨论(0)
  • 2020-12-16 10:53

    You're looking for an equivilent of PHP's br2nl(). This should do the job:

    function br2nl(str) {
        return str.replace(/<br\s*\/?>/mg,"\n");
    }
    
    0 讨论(0)
  • 2020-12-16 11:02

    A cheap function:

    function brToNewLine(str) {
        return str.replace(/<br ?\/?>/g, "\n");
    }
    

    es.

    vat str = "Hello<br \>world!";
    var result = brToNewLine(str);
    

    The result is: "Hello/nworld!"

    0 讨论(0)
提交回复
热议问题