【问题标题】:How to delete everything after the second " " in a string, using the replace(), slice() or other function in google sheets如何使用替换(),切片()或谷歌表格中的其他函数删除字符串中第二个“”之后的所有内容
【发布时间】:2020-02-01 02:00:03
【问题描述】:

所以我目前正在开发一个函数来使用应用脚本 api 格式化 Google 表格上的一些输入单元格。

现在我正在从几个单元格中获取输入并稍微格式化它们以符合手动生成的系统。

一个单元格是一个学校名称单元格。有时这些名称往往很长,我在 javascript 方面不是超级经验,但现在我正在从一个单元格中获取一个参数,我将如何定义该参数的变量,以便它只接受单元格中直到第二个空格的所有内容。

前:
单元格 A#:填空高中联盟

输出:高位填空

/**
*Generates a Trip Key
*
*@param DateColumn Date 
*@param SchoolColumn School name
*@param LocationColumn Location
*@customfunction
*/
function GENERATEKEY(DateColumn, SchoolColumn, LocationColumn) {
  var DateConver = Utilities.formatDate(DateColumn, SpreadsheetApp.getActive().getSpreadsheetTimeZone(), "MM.dd.yyyy");
  var SchoolClean = SchoolColumn.replace(

  return DateConver + " " + SchoolColumn + " " + "@" + " " +  LocationColumn  
}

【问题讨论】:

    标签: javascript string google-apps-script google-sheets custom-function


    【解决方案1】:

    使用正则表达式匹配直到第二个空格的所有内容。

    var SchoolClean = SchoolColumn.replace(/^(\S*\s*\S*).*/, '$1');
    

    \S 匹配非空白字符,\s 匹配空白。所以\S*\s*\S* 匹配非空格,后跟空格,后跟非空格。然后.* 匹配字符串的其余部分。替换为$1,这正是括号内部分匹配的内容。

    【讨论】:

      【解决方案2】:
      function selectText(data) {
        var idx1=data.indexOf(' ');//location of first space
        var idx2=data.indexOf(' ',idx1+1);//starts looking for second space 1 after first space.
        var s=data.slice(0,idx2);//idx2 + 1 if you want the second space
        return s;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-07-21
        • 1970-01-01
        • 2022-08-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多