• js字符转义备忘

    日期:2009-10-19 | 分类:Coding

    好吧,又是令人痛恨的js。现在用perl写个Tenjin模板库的wrapper,变量付进去,会需要到不同格式间的转换。

    sub txt2htmljs {
        my ($content) = @_;
        $content =~ s/"/"/gs;
        $content =~ s/\\/\\\\/gs;
        $content =~ s/'/\\'/gs;
        $content =~ s/(\r?\n)/\\n/gs;
        return $content;
    }


    sub txt2js {
        my ($content) = @_;
        $content =~ s/\\/\\\\/gs;
        $content =~ s/"/\\"/gs;
        $content =~ s/'/\\'/gs;
        $content =~ s/(\r?\n)/\\n/gs;
        return $content;
    }

    以上两个函数的区别在于,前一个是给模板里的html元素的js回调用的,比如onClick="foo('[== $STR =]')",这种。后一个是给模板里的纯的js用的,就比如<script>里面写的var bar='[== $STR =]'。

    我不是专业web开发者,以上还没充分测试过的,用不了请反馈给我


    随机文章:

    I hate js 2009-03-10
    多维度思考 2009-12-09
    flac2mp3脚本 2007-10-17

    收藏到:Del.icio.us