2015-11-04 108 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>