HTML代码转换为JavaScript字符串

时间:2024-02-24 07:57:25
<script type="text/javascript">
    function javascript() {
        var isArraySel = $("#arrays-sel").prop("checked");
        var htmlArr = $("#content").val().replace(/\\/g, "\\\\").replace(/\\/g, "\\/").replace(/\\'/g, "\\\\'").replace(/\"/g, "\\\"").split(\'\n\');
        var len = htmlArr.length;
        var outArr = [];
        if (isArraySel) {
            outArr.push("[");
            jQuery.each(htmlArr, function (index, value) {
                if (value !== "") {
                    if (index === len - 1) {
                        outArr.push("\"" + value + "\"");
                    } else {
                        outArr.push("\"" + value + "\",\n");
                    }
                }

            });
            outArr.push("].join(\"\");");
        } else {
            jQuery.each(htmlArr, function (index, value) {
                if (value !== "") {
                    if (index === len - 1) {
                        outArr.push("\"" + value + "\";");
                    } else {
                        outArr.push("\"" + value + "\"+\n");
                    }
                }
            });
        }
        $("#result").val(outArr.join(""));
    }