Home > Back-end >  .replace() not working for escaping back slashes in JavaScript for Google Tag Manager
.replace() not working for escaping back slashes in JavaScript for Google Tag Manager

Time:04-01

I'm trying to dynamically populate schema into my company's blog posts. Most things work just fine, but URLs, for some reason, have escape characters behind each /. Examples are denoted by '**' below in the schema markup

<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>

My code for replacing the escape characters is:

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

where .schema-blog-image is the class selector for the blog's featured image.

In the above 'url' fields, I was able to get the URL in no problem using Google Tag Manager's JavaScript variable to get the image source from the HTML using the same class name. However, when I tried to use the function above using the same class name but for "image," it returns an empty string (as seen above).

Some Googling led me to try return JSON.stringify(postUrl) (while removing the cleanPostUrl var), but that just gives me \x22\x22 as a result.

The function above worked perfectly when I tried it on the W3 Schools Try It Yourself editor, so I'm not sure what else to do to make the regex work.

None of this replaced the escape characters.

CodePudding user response:

try this

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

CodePudding user response:

So, I got this figured out by following a guide I found on Moz.com

Here's what the tag code looks like now:

<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>

My variables are just the raw element attributes (e.g. the image is gotten from using a DOM Element variable, targeting the CSS Selector I provided, and using the src attribute to get the URL). The difference now is that my schema is now wrapped inside a variable inside a function, where I can now pass all these variables through as true strings. From there, we can create a var script and use that to create a new script HTML element with the properties I need and insert it where I need it.

Since I was able to use these variables as true strings within the variable 'data' itself, I no longer need to worry about escaping characters.

Hope this helps someone else!

  • Related