Julian R Julian R - 4 months ago 11
Javascript Question

Javascript .split () function with multiple conditions

Hey there I am having some troubles working with the split function within GTM, I want to read the body class and return a singular word. e.i.

<body class="landing-holidays subscribe-page"></body>


Returning just 'holidays', my challenge is to get the split to just pull the second value. Code:

function () {
var product = document.getElementsByTagName('body')[0];
if (product != undefined) {
var product_id = product.getAttribute('class');
if (product_id != null)
return product_id.split('-')[1];
}
return null
}


I get "holidays subscribe". When I need "holidays", any insight?

Answer

You can use a regular expresion. change .split('-') to .split(/[\-\s]/)

var product = document.getElementsByTagName('div')[0];

function run() {
  if (product != undefined) {
    var product_id = product.getAttribute('class');
    if (product_id != null) {
      var a = product_id.split(/[\-\s]/);
      for (var i = 0, l = a.length; i < l; i++) {
        if (a[i] === 'holidays') {
          return a[i];
        }
      }
    }

  }
}
alert(run())
<div class="landing-holidays subscribe-page"></div>