2

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?

Julian R
  • 23
  • 4
  • I don't understand how this is an "exact duplicate". – 8protons May 10 '16 at 19:59
  • `document.body.className.match(/landing-(.+?)\b/);` – dfsq May 10 '16 at 20:06
  • There is a [`classList`](https://developer.mozilla.org/en-US/docs/Web/API/Element/classList) interface that will return, well, a list of the classes on the element. This may or may not help you. – Heretic Monkey May 10 '16 at 20:10
  • 1
    @8protons The OP appears (but this appearance *may* be deceiving, if the OP clarifies the problem later) to want to split a string on both hyphens and spaces and get the second element from such a split-list. The OP already understands how to get the second element from a list, so the only remaining question is how to split on multiple characters, which is exactly what the duplicate target addresses. – apsillers May 10 '16 at 20:13
  • @apsillers Wow. That completely makes sense, thank you for explaining. I'm not experienced enough to see through the language (in this case, JS) syntax/semantics of question and details, so that made no sense to me until I read your point. Makes me kind of wish leaving feedback for flags was required so that way users could learn and understand what dictates a question worth closing. – 8protons May 10 '16 at 20:14

1 Answers1

2

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>
Roger
  • 3,226
  • 1
  • 22
  • 38
  • aaa, I was trying to use reg ex without the brackets. SMH thank you for the reminder to drink more coffee! – Julian R May 10 '16 at 20:09