2017-07-18 80 views
0

我正面臨字符串內單引號和雙引號的問題。在我的情況下,它是:JS允許單引號和雙引號打印

var Des = "It's alright. We are the so-called "Vikings" from the north."; 

我想顯示此字符串,因爲它是。我有一個隨機字符串。有時候,它只有單引號,雙引號,有時候什麼也沒有。我想到目前爲止

代碼是:

var fieldData = "<input type='text' name='desc' value='\""+Desc+"\"'>"; 

但它不工作。

回答

0

您需要先使用\"轉義Des字符串中的雙引號。

然後,您需要HTML編碼value屬性,以便字符串內的引號不會干擾分隔屬性本身的引號。正如你已經標記jQuery,你可以很簡單地通過使用val()來做到這一點,因爲它爲你編碼值。試試這個:

var Des = "It's alright. We are the so-called \"Vikings\" from the north."; 
 
var $input = $('<input type="text" name="desc">').val(Des); 
 
$input.appendTo('body');
/* only used here to make the output fully visible without scrolling */ 
 
input { width: 325px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

+0

我有一個動態的字符串。我需要用整個字符串替換「with \」 –

+0

這是正確的。 –

+0

但我無法將單引號轉換爲'\和雙引號「\。:( –