.replace()不适用于Google标记管理器JavaScript中的转义反斜杠



我正在尝试将模式动态填充到我公司的博客文章中。大多数事情都很正常,但由于某种原因,URL的每个/后面都有转义符。示例在下面的模式标记中用"**"表示

<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "BlogPosting",
"headline": "HHHunts Commitment To RVA",
"image": "",  
"author": {
"@type": "Organization",
"name": "HHHunt"
"url": "https://hhhunt.com"
},  
"publisher": {
"@type": "Organization",
"name": "HHHunt",
"logo": {
"@type": "ImageObject",
**"url": "https://assets-global.website-files.com/61d6f3d648b8c96670b238ab/61d86f26213077625ab3a90e_logo-130.png"**
}
},
"datePublished": "2022-03-28",
"articleBody": "When ... ‍", // shortened
**"thumbnailUrl": "https://assets-global.website-files.com/61d6f3d648b8c989b9b238c0/624311d33025d92e76fb34b9_Habitat-for-Humaity-(2).jpg",**
"timeRequired": "PT3M",
"description": "Growing up in Richmond, VA, Harry H. Hunt, III has always held a special place in heart for RVA and made a commitment to supporting and investing in the region.",
}
</script>

我替换转义字符的代码是:

function() {
var postUrl = document.getElementsByClassName('schema-blog-image')[0].innerText;
var cleanPostUrl = postUrl.replace(/[\]/g,"")
return cleanPostUrl;
}

其中.schema博客图像是博客特色图像的类选择器。

在上面的"url"字段中,我可以使用Google Tag Manager的JavaScript变量从使用相同类名的HTML中获取图像源,从而毫无问题地获取url。然而,当我尝试使用上面的函数时,使用相同的类名;图像,";它返回一个空字符串(如上所示(。

一些谷歌搜索让我尝试了return JSON.stringify(postUrl)(同时删除了cleanPostUrl变量(,但结果只给了我x22x22

当我在W3 Schools Try It Yourself编辑器上尝试上面的函数时,它运行得很好,所以我不确定还需要做什么才能使regex正常工作。

所有这些都没有替换转义符。

尝试这个

var cleanPostUrl= JSON.stringify(postUrl);
var data = JSON.parse(cleanPostUrl);

所以,我按照在Moz.com 上找到的指南找到了答案

以下是标签代码现在的样子:

<script>
(function(){
var data = {
"@context": "https://schema.org",
"@type": "BlogPosting",
"headline": {{Post Title}},
"image": {{Post Image}},
"author": {
"@type": "Organization",
"name": "HHHunt",
"url": "https://hhhunt.com"
},  
"publisher": {
"@type": "Organization",
"name": "HHHunt",
"logo": {
"@type": "ImageObject",
"url": {{Logo}}
},
},
"datePublished": {{ISO Date}},
"articleBody": {{Post Content}},
"thumbnailUrl": {{Post Image}},
"timeRequired": "PT" + {{Duration}} + "M", // I had to adjust this line to allow a string concat using a variable
"description": {{Meta Description}},
}
var script = document.createElement('script');
script.type = "application/ld+json";
script.innerHTML = JSON.stringify(data); 
document.getElementsByTagName('footer')[0].appendChild(script); // write the script to my <footer> tag
})(document);
</script>

我的变量只是原始元素属性(例如,图像是通过使用DOMElement变量获得的,目标是我提供的CSS Selector,并使用src属性获得URL(。现在的区别是,我的模式现在被封装在函数中的一个变量中,在这里我可以将所有这些变量作为真正的字符串传递。从那里,我们可以创建一个var脚本,并使用它创建一个具有我需要的属性的新脚本HTML元素,并将其插入到我需要的地方。

由于我能够在变量"data"中使用这些变量作为真正的字符串,所以我不再需要担心转义字符。

希望这能帮助其他人!

最新更新