嘿,我在使用 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/