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?

5
  • I don't understand how this is an "exact duplicate". Commented May 10, 2016 at 19:59
  • document.body.className.match(/landing-(.+?)\b/); Commented May 10, 2016 at 20:06
  • There is a classList interface that will return, well, a list of the classes on the element. This may or may not help you. Commented May 10, 2016 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. Commented May 10, 2016 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. Commented May 10, 2016 at 20:14

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

1 Comment

aaa, I was trying to use reg ex without the brackets. SMH thank you for the reminder to drink more coffee!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.