iT邦幫忙

0

JavaScript replace 取代 \" 問題

chan15 2010-01-05 08:58:3817253 瀏覽
<?php
if (isset($_POST['getJson'])) {
	$arr = array('test' => '\'\"1234\"\'');
	echo json_encode($arr);
	exit;
}
?>

<html xmlns="http://www.w3.org/1999/xhtml">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>json</title>
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"></script>



<div id="json"></div>
<input name="btnJson" type="button" id="btnJson" value="get" />
<script>
$(function() {
	$('#btnJson').click(function() {
		$.post('json.php', {getJson: 1}, function($res) {
			$('#json').html($res.test.replace(/\"/g, '"'));
		} , 'json');
	});
});
</script>

為了儲存json格式正確,所以會把會員輸入的'跟"轉成\'跟\"存進去
撈出來的時候發現\'會自動轉成',但\"不會,所以想用replace的方式取代
但這樣下好像不對replace(/\"/g, '"'),請教該如何達到目的?

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

10
fillano
iT邦超人 1 級 ‧ 2010-01-05 11:51:23
最佳解答

你的replace用法有錯,取代過的是回傳值,不是原來的字串。

我試了一下,這樣就可以正確取代:

<pre class="c" name="code">
var str = 'all man "this" is the all.';
var res = str.replace(/"/g, '\\"');
alert(res);

Javascript
就等fillano大大出手了,推 bbb

我要發表回答

立即登入回答