You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript字符串截取方法及基于Body类生成DFP定向代码咨询

针对你的两个问题,我来分别给出实用的解决方案:

1. 如何使用JavaScript截取字符串的部分内容?

JavaScript提供了多种灵活的字符串截取方法,你可以根据具体场景选择:

  • slice(start[, end])(推荐)
    这是最通用的截取方法,支持正负索引,start是起始位置(负数表示从末尾倒数),end是结束位置(可选,不包含该位置的字符)。

    const str = "Hello JavaScript";
    console.log(str.slice(0, 5)); // 输出 "Hello"
    console.log(str.slice(-10)); // 输出 "JavaScript"(从倒数第10位截取到末尾)
    
  • substring(start[, end])
    和slice类似,但会自动处理start大于end的情况(交换两者位置),不过不支持负数索引。

    const str = "Hello JavaScript";
    console.log(str.substring(6, 16)); // 输出 "JavaScript"
    console.log(str.substring(16, 6)); // 结果同上,自动交换参数
    
  • substr(start[, length])
    注意这个方法已被标记为“过时”但仍被主流浏览器支持,它的第二个参数是截取长度而非结束索引,start同样支持负数。

    const str = "Hello JavaScript";
    console.log(str.substr(6, 10)); // 输出 "JavaScript"
    console.log(str.substr(-10, 10)); // 输出 "JavaScript"
    
  • 分隔符场景的截取(ES6方式)
    如果需要根据特定分隔符拆分截取,可以结合split和解构赋值:

    const url = "https://example.com/blog/post1";
    const [, , , postId] = url.split('/');
    console.log(postId); // 输出 "post1"
    
2. 如何根据body元素的CSS类确定页面分类并生成DFP定向代码?

针对你给出的body类<body class="archive category category-basketball category-23872 content-sidebar">,我们可以通过正则匹配+类名筛选的方式,精准提取目标分类并生成DFP代码:

实现思路

  1. 获取body的所有类名并转为数组,方便后续处理;
  2. 用正则筛选出category-开头但非纯数字后缀的类(排除category-23872这类ID类);
  3. 提取分类值并调用DFP API设置定向参数。

完整代码示例

// 获取body类名并转为数组
const bodyClasses = Array.from(document.body.classList);

// 筛选符合规则的分类类名:以category-开头,后缀不是纯数字
const validCategoryClasses = bodyClasses.filter(className => {
  return /^category-(?!\d+$)/.test(className);
});

// 生成DFP定向代码
if (validCategoryClasses.length > 0) {
  // 提取第一个分类值(如果有多个分类,可循环处理)
  const categoryValue = validCategoryClasses[0].replace(/^category-/, '');
  googletag.pubads().setTargeting("category", categoryValue);
}

补充说明

  • 如果页面存在多个有效分类(比如category-basketball category-sports),可以批量设置定向:
    const categoryValues = validCategoryClasses.map(cls => cls.replace(/^category-/, ''));
    googletag.pubads().setTargeting("category", categoryValues);
    
  • 正则/^category-(?!\d+$)/的逻辑是:^category-确保前缀正确,(?!\d+$)是负向前瞻,排除后缀全为数字的情况,兼容带数字的分类名(比如category-basketball-2024)。

内容的提问来源于stack exchange,提问作者blogjunkie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:59:41