2015-11-04 106 views
-4

我想要替換JSON對象內的字符串。 我的JSON對象看起來是這樣的:如何替換JSON對象輸出中的字符串?

{ 
    "type":   "text", 
    "timeTrigger": 34, 
    "title":  "Sherlock Holmes", 
    "subtitle":  "Detective", 
    "picture":  "images/content/placehold.png", 
    "intro":  "Sherlock Holmes is a fictional detective created by British author Sir Arthur Conan Doyle. [gallery] Holmes is known for his astute logical reasoning..." 
      }, 

我想換成是標籤[gallery]到圖像對象。

我嘗試這樣做:

var mystring = data.text; 
mystring.replace('[gallery]' , 'replaced!'); 

這:

var stringified = JSON.stringify(json); 
stringified = stringified.replace('"[gallery]": "replaced"'); 

雙方將導致沒有任何改變。最後一個,我認爲只有當您想要更改JSON中的鍵>值時才使用,但我只想過濾掉圖庫標記並將其替換爲圖像。因此輸出將會將[gallery]替換爲圖像對象。

歡迎任何建議和代碼。 在此先感謝。

UPDATE

腳本波紋管將替換包含[gallery]新的東西的data.text,但這隻適用於的console.log而不是在頁面上相同的文字..

var mystring = data.text; 
console.log(mystring.replace('[gallery]', '=========dsiuhfodsa=========')); 
+1

是。是的,這在現實領域當然是可能的。 – deceze

+0

這不是JSON或JavaScript的功能。有很多模板語言(用JS編寫的編譯器)可讓您以字符串的形式表示模板,並且可以將字符串存儲爲JSON。 – Quentin

+3

你的問題是*實際*「是否可以替換字符串中的文本」(谷歌「替換字符串JavaScript」),答案是顯而易見的是。無論數據來源如何,它都不會改變問題的簡單性。 – h2ooooooo

回答

1

隨着.replace()功能,並使用與之後的第二前鋒這些特殊字符的正則表達式削減貪婪其中術語[gallery]i不區分大小寫的所有實例匹配g,也不要忘記用反斜線來逃避[]以匹配它們。

JS Fiddle

var div = document.getElementById('intro'), 
 
\t data = { 
 
    \t \t "type" \t \t : \t "text", 
 
    \t \t "timeTrigger": 34, 
 
    \t \t "title" \t \t : \t "Sherlock Holmes", 
 
    \t \t "subtitle" \t : \t "Detective", 
 
    \t \t "picture" \t : \t "images/content/placehold.png", 
 
    \t \t "intro" \t \t : \t "Sherlock Holmes is a fictional detective created by British author Sir Arthur Conan Doyle. [gallery] Holmes is known for his astute logical reasoning..." 
 
      }; 
 
var intro = data['intro']; 
 
div.innerHTML = intro.replace(/\[gallery\]/ig, '<img src="//placehold.it/100x100?image">');
<div id="intro"></div>