通过JavaScript将textarea换行符转换为<p>和<br/>标签</p>

时间:2011-09-07 15:15:04

标签: javascript html textarea newline string-formatting

我正在使用html表单中的textarea,并且我正在尝试使用<p><br/>标记将其内容重新格式化为有效的html格式。

我写了这个脚本,它似乎工作但我想确保我没有遗漏任何东西。所以我要求反馈。我知道我没有考虑用户可能明确输入html标签的可能性,但这没问题,因为我将以PHP的形式发布结果。

提前致谢。

输出示例:

<p>Line 1<br/>Line 2</p><p>Line 4<br/><br/><br/>Line 7</p>

和代码:

function getHTML() {

    var v = document.forms[0]['txtArea'].value;
    v = v.replace(/\r?\n/gm, '<br/>');
    v = v.replace(/(?!<br\/>)(.{5})<br\/><br\/>(?!<br\/>)/gi, '$1</p><p>');
    if (v.indexOf("<p>") > v.indexOf("</p>")) v = "<p>" + v;
    if (v.lastIndexOf("</p>") < v.lastIndexOf("<p>")) v += "</p>";
    if (v.length > 1 && v.indexOf("<p>") == -1) v = "<p>" + v + "</p>";
    alert(v);

}

请注意,这是一个旨在成为CMS一部分的代码,我所关心的JavaScript是用这两个标签重建textarea结果。所见即所得的问题......

3 个答案:

答案 0 :(得分:6)

这就是我想出来的。

function encode4HTML(str) {
    return str
        .replace(/\r\n?/g,'\n')
        // normalize newlines - I'm not sure how these
        // are parsed in PC's. In Mac's they're \n's
        .replace(/(^((?!\n)\s)+|((?!\n)\s)+$)/gm,'')
        // trim each line
        .replace(/(?!\n)\s+/g,' ')
        // reduce multiple spaces to 2 (like in "a    b")
        .replace(/^\n+|\n+$/g,'')
        // trim the whole string
        .replace(/[<>&"']/g,function(a) {
        // replace these signs with encoded versions
            switch (a) {
                case '<'    : return '&lt;';
                case '>'    : return '&gt;';
                case '&'    : return '&amp;';
                case '"'    : return '&quot;';
                case '\''   : return '&apos;';
            }
        })
        .replace(/\n{2,}/g,'</p><p>')
        // replace 2 or more consecutive empty lines with these
        .replace(/\n/g,'<br />')
        // replace single newline symbols with the <br /> entity
        .replace(/^(.+?)$/,'<p>$1</p>');
        // wrap all the string into <p> tags
        // if there's at least 1 non-empty character
}

您需要做的就是使用textarea的值调用此函数。

var ta = document.getElementsByTagName('textarea')[0];
console.log(encode4HTML(ta.value));

答案 1 :(得分:0)

v = v.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")
    .replace(/([^\r\n]+)\r?\n\r?\n/g, "<p>$1</p>")
    .replace(/\r?\n/g, "<br />");

答案 2 :(得分:-1)

哦,你试图将html代码传递给后端?这就是我们所说的XSS漏洞。

http://en.wikipedia.org/wiki/Cross-site_scripting

ubb代码怎么样?

http://en.wikipedia.org/wiki/UBB.threads

相关问题