JavaScript中的单引号和双引号报错的解决方法

前端技术 2023/09/04 JavaScript

在使用JavaScript显示消息或者传递字符数据的时候,经常会碰到数据中夹杂单引号(\')或者双引号(\"),这种语句往往会造成JavaScript报错。对此一般采用/\'或者/\"的解决。

例如:

Alert(\"this is test \"message\"!\"); 
Alert(\'this is test \'message\'!\');

一般会改成以下语句

Alert(\"this is test /\"message/\"!\"); 
//或者 
Alert(\"this is test \'message\'!\"); 
Alert(\'this is test /\'message/\'!\');

以上如果只在脚本中使用或者没有太复杂的数据字符连接,则已经解决了这个问题。

但是如果存在比较复杂的数据字符连接的时候,特别是某些由服务器组合的JavaScript语句时候可以考虑将单引号(\')和者双引号(\"),用转义序列(escape sequence )输出。

例如上面的语句可以转变成以下的格式:

Alert(\"this is test /u0022message/u0022!\"); 
Alert(\'this is test /u0027message/u0027!\');

补充一些常用的编码

字符说明 Unicode 转义序列
长破折号 (—) /u2014
注册符号 (R) /u00AE
版权符号 (c) /u00A9
商标符号 (?) /u2122
欧元符号 (

本文地址:https://www.stayed.cn/item/10451

转载请注明出处。

本站部分内容来源于网络,如侵犯到您的权益,请 联系我

我的博客

人生若只如初见,何事秋风悲画扇。