RegEx Inject ads on React or Vuejs blog post

How to inject google ads with Regular expression on Single page apps (SPA)

Google ads or any ad can be injected using the standard regular expression. Below is an example of how injected ads looks like.


I suggest you check this blog post on how to inject ads on React js app. One thing i found that was, \r\nRegular expression are powerful technique used to inject more than one \r\nad on a single page.

So here is the simple solution

 const reg = /(your-ad-spot)/gm;
            const postwithad = mainPostBody.replace(
              reg,
              `<script async src=\"https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js\"></script>
<ins class=\"adsbygoogle\"
    
style=\"display:block; text-align:center;\"
    
data-ad-layout=\"in-article\"
    
data-ad-format=\"fluid\"
    
data-ad-client=\"ca-pub-\"
    
data-ad-slot=\"\">
</ins>
<script>
     (adsbygoogle =
window.adsbygoogle || []).push({});
</script>`
            );