JS处理字符串中的特殊字符

来源:互联网 发布:做政府数据库的公司 编辑:程序博客网 时间:2024/05/16 02:22

项目组内有同事用JS组装JSON是字符串拼接,结果出问题了(建议采用json插件),没重写,在基础上进行修复,导致问题的原因是字符串中有换行符或者空格。

处理方法:把这些特殊字符找到替换成转义字符。

利用Jquery.json插件里面的quoteString方法。

下载地址:http://code.google.com/p/jquery-json/downloads/list

例子代码,进行记录备份,以备不时之需:

<script type="text/javascript" src="js/jquery.js"></script><script type="text/javascript">varescapeable = /["\\\x00-\x1f\x7f-\x9f]/g,meta = {'\b': '\\b','\t': '\\t','\n': '\\n','\f': '\\f','\r': '\\r','"' : '\\"','\\': '\\\\'};var replaceEscape = function(string){if ( string.match( escapeable ) ) {return '"' + string.replace( escapeable, function( a ) {var c = meta[a];if ( typeof c === 'string' ) {return c;}c = a.charCodeAt();return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16);}) + '"';}return   string  ;}$(document).ready(function(){ $('#commit').click(function(){ var name = $('#name').val(); alert(replaceEscape(name)); }); });</script><body><div><textarea  id="name"></textarea><input type="button" value="提交" id="commit" ></div></body>

太阳系 - http://blog.csdn.net/fellting

原创粉丝点击