简体   繁体   中英

Run a javascript on regex pattern match url (Blogger)

I'm trying to load a javascript on several pages but I only on pages which the url matches with a specific pattern.

The following code works for specific pages but it doesn't accept any wildcard or regex

<b:if cond='data:blog.url == &quot;https://mywebsite.com/yyyy/mm/article.html&quot;'>
<script src='https://javascritp.js'/>
</b:if>

The closest thing I found is described here but since my website is running on Blogger I don't know how to use that code.

Any suggestion or help please?

Blogger conditional statements don't provide pattern matching capability. It would be easier to implement what you require via JavaScript directly in the Blogger template -

An example code would look like -

if(window.location.href.match(/Regex-Condition/){
    var script = document.createElement('script'); script.type = 'text/javascript'; 
    script.src = 'URL-Of-The-Script-You-Want-To-Load';script.async=true;
    var insertScript = document.getElementsByTagName('script')[0]; insertScript.parentNode.insertBefore(script, insertScript);
}

Other than this, you can also take a look at Lambda expressions (Refer to How to use Google Blogger Lambda Operators )

Hi and thank you for your feedback! While I was waiting for some reply I realized I've to use JavaScript as you said.

I was testing this code but it looks something is wrong:

<script type='text/javascript'>

var pattern = new RegExp(&#39;mywebsite\.com\/(200[8-9]|201[0-6])\/&#39;);
if (pattern.test(document.location.href)) {

}

</script>

I've two main concerns:

  • if the regex is correct
  • between the brackets I've to execute some code which includes Blogger conditional statements, div and plain JavaScript. Does this code need some special attention?

Thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM