替换String中的所有双引号 [英] Replace all double quotes within String

查看:134
本文介绍了替换String中的所有双引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从数据库中检索数据,其中该字段包含带有HTML数据的String。我想替换所有的双引号,以便它可以用于 jQuery parseJSON

I am retrieving data from a database, where the field contains a String with HTML data. I want to replace all of the double quotes such that it can be used for parseJSON of jQuery.

使用Java,我试图用...替换引号。

Using Java, I am trying to replace the quotes using..

details.replaceAll("\"","\\\"");
  //details.replaceAll("\"","&quote;"); details.replaceAll("\"","&#34");

结果字符串未显示所需的更改。
O'Reilly 文章规定使用Apache字符串工具。还有其他方法吗?

The resultant string doesn't show the desired change. An O'Reilly article prescribes using Apache string utils. Is there any other way??

是否有正则表达式或我可以使用的东西?

Is there a regex or something that I could use?

推荐答案

以下是

String details = "Hello \"world\"!";
details = details.replace("\"","\\\"");
System.out.println(details);               // Hello \"world\"!

请注意,字符串是不可变,因此仅仅执行 details.replace(\,\\\)是不够的。您必须将变量 details 重新分配给结果字符串。

Note that strings are immutable, thus it is not sufficient to simply do details.replace("\"","\\\""). You must reassign the variable details to the resulting string.

使用

details = details.replaceAll("\"","&quote;");

相反,结果

Hello &quote;world&quote;!

这篇关于替换String中的所有双引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆