Javascript .split() 函数具有多个条件

标签 javascript google-tag-manager

嘿,我在使用 GTM 中的 split 函数时遇到了一些麻烦,我想读取主体类并返回一个单数单词。 e.i.

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

仅返回“假期”,我的挑战是如何进行分割以拉出第二个值。代码:

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
}

我得到“假期订阅”。当我需要“假期”时,有什么见解吗?

最佳答案

您可以使用正则表达式。将 .split('-') 更改为 .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>

关于Javascript .split() 函数具有多个条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37147729/

相关文章:

javascript - 如何使用 Amplify with Javascript 返回 AWS 用户池中的用户状态?

javascript - 让 jsdoc 和 Crockford 的设计模式相处融洽

javascript - 在 Google Analytics 中,为什么事件标签=(未设置)

javascript - 捕获多个 slider 元素上的鼠标悬停

javascript - 如何在 Google 跟踪代码管理器中的不同 HTML 位置添加标签?

javascript - 如果同一页面上有多个 Google map ,单击任何标记都会突出显示最底部的 map 标记

javascript - Mongoose:TypeError:十六进制不是函数

javascript - 使一个元素的上边距始终与另一个元素的计算高度相同

ios - 在 iOS 上使用 Google 跟踪代码管理器传递 UTM 参数

tags - Floodlight 和 Google 跟踪代码管理器