我正在尝试替换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标签并将其替换为图像。因此,输出会将[gallery]
替换为图像对象。
欢迎任何建议和代码。 提前谢谢。
更新
下面的脚本将使用新的东西替换包含[gallery]
的data.text,但这仅适用于console.log,而不适用于页面上的相同文本..
var mystring = data.text;
console.log(mystring.replace('[gallery]', '=========dsiuhfodsa========='));
答案 0 :(得分:1)
使用.replace()
函数并在第二个正斜杠贪婪g
之后使用带有这些特殊字符的正则表达式,它匹配所有出现的术语[gallery]
和i
不区分大小写,另外不要忘记使用反斜杠转义[
和]
以匹配它们。
var div = document.getElementById('intro'),
data = {
"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..."
};
var intro = data['intro'];
div.innerHTML = intro.replace(/\[gallery\]/ig, '<img src="//placehold.it/100x100?image">');
<div id="intro"></div>