通过 JavaScript 将文本区域换行符转换为 <p> 和 <br/> 标记



我在html表单中使用文本区,我试图通过使用<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是重建文本区结果与这2个标签。有点像所见即所得的问题…

我是这么想的

function encode4HTML(str) {
    return str
        .replace(/rn?/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));
v = v.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")
    .replace(/([^rn]+)r?nr?n/g, "<p>$1</p>")
    .replace(/r?n/g, "<br />");

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

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

用ubb代码代替怎么样?

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

最新更新