【问题标题】:How to separate text within a cell of a google sheets by Capital Letter如何用大写字母分隔谷歌表格单元格中的文本
【发布时间】:2020-06-15 09:27:45
【问题描述】:

我需要帮助拆分 Google 表格电子表格单元格中的文本。我拥有的数据缺少以大写字母开头的每个单词之间的空格。例如,单元格 A1 包含“BarbaraSmith”我需要一个谷歌脚本,它将 A1 中的内容分隔到 B1 和 C1,其中 B1 将包含 Barbara,C1 将包含 Smith。

谢谢

【问题讨论】:

  • var str="BarbaraSmith" ; var patt = new RegExp("[A-Z][^A-Z]*", "g"); str.match(patt);这将为您提供数组中的这些单词

标签: javascript google-sheets


【解决方案1】:

查看此链接以了解如何创建自定义函数 https://developers.google.com/apps-script/guides/sheets/functions#creating_a_custom_function

将此代码复制到该自定义函数中

function CSepString(from) {
 var patt = new RegExp("[A-Z][^A-Z]*", "g");
 return [from.match(patt)];
}

来到谷歌表格并像这样使用它

=CSepString(A1)

【讨论】:

  • 效果很好。谢谢你这么快的回复。
【解决方案2】:

使用for循环,检查字母是否大写,然后将收集到的所有字符移动到单词数组中。

function splitWords(str) {
  const start = "A".charCodeAt(0);
  const end = "Z".charCodeAt(0);
  const words = [];

  let word = "";
  for (let i = 0; i < str.length; i++) {
    const code = str.charCodeAt(i);
    if (code >= start && code <= end) {
      if (word) {
        words.push(word);
        word = "";
      }
    }
    word = `${word}${str[i]}`;
  }
  words.push(word);
  return words;
}

console.log(splitWords("BarbaraSmith"));

【讨论】:

  • 谢谢 - 我也试试看。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-27
  • 2016-06-11
  • 2023-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多