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

在Google Sheet脚本中使用string函数:如何提取substring及获取字符串长度

Google Apps Script 字符串操作指南

Google Sheets 配套使用的脚本为 Google Apps Script,其字符串相关操作逻辑和原生 JavaScript 完全一致,具体用法如下:

1. 获取字符串长度

直接调用字符串的length属性即可得到字符总数:

// 基础示例
function getStrLength() {
  const targetStr = "示例测试字符串";
  const strLength = targetStr.length;
  console.log(strLength) // 输出结果为7
}

// 从表格单元格读取内容并计算长度的示例
function getCellStrLength() {
  const sheet = SpreadsheetApp.getActiveSheet();
  const cellValue = sheet.getRange("A1").getValue().toString();
  const cellStrLength = cellValue.length;
}

2. 提取子字符串

常用3种方法,可根据场景选择:

  • substring(起始索引, 结束索引)
    索引从0开始计数,结束索引为可选参数,不填则默认截取到字符串末尾。如果起始索引大于结束索引,方法会自动交换两个参数的位置,不支持负索引。
    代码示例:

    const demoStr = "Hello Google Sheets";
    // 截取从索引6开始到末尾的内容
    const sub1 = demoStr.substring(6); // 返回结果:Google Sheets
    // 截取索引6到12之间的内容(不包含索引12的字符)
    const sub2 = demoStr.substring(6, 12); // 返回结果:Google
    
  • slice(起始索引, 结束索引)
    基础用法和substring一致,区别是支持负索引(-1代表最后一个字符的索引,-2代表倒数第二个,以此类推),如果起始索引大于结束索引不会自动交换参数,会返回空字符串。
    代码示例:

    const demoStr = "Hello Google Sheets";
    // 截取最后6个字符
    const sub3 = demoStr.slice(-6); // 返回结果:Sheets
    // 截取索引6到倒数第7个字符之间的内容
    const sub4 = demoStr.slice(6, -7); // 返回结果:Google
    
  • substr(起始索引, 截取长度)
    第二个参数为要截取的字符总数,可选,不填则截取到末尾,也支持负的起始索引。注意该方法已被标记为遗留方法,目前虽可正常使用,但更推荐优先使用前两种方法。
    代码示例:

    const demoStr = "Hello Google Sheets";
    // 从索引6开始截取6个字符
    const sub5 = demoStr.substr(6, 6); // 返回结果:Google
    

注意:如果你是在Google Sheets单元格公式中使用,而非脚本编辑器中,对应的内置函数为LEN()(获取长度)、LEFT()/RIGHT()/MID()(提取子串),不要和脚本语法混淆。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 15:36:04