簡體   English   中英

如何刪除字符串中第二個“”之后的所有內容,使用 Google 表格中的 replace()、slice() 或其他函數

[英]How to delete everything after the second " " in a string, using the replace(), slice() or other function in google sheets

所以我目前正在開發一個函數來使用應用程序腳本 api 在 Google Sheets 上格式化一些輸入單元格。

現在我從幾個單元格中獲取輸入並稍微格式化它們以符合手動生成的系統。

一個單元格是學校名稱單元格。 有時這些名稱往往很長,我在 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  
}

使用正則表達式將所有內容匹配到第二個空格。

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

\\S匹配非空白字符, \\s匹配空白字符。 所以\\S*\\s*\\S*匹配非空格后跟空格后跟非空格。 然后.*匹配字符串的其余部分。 替換為$1 ,這正是括號內部分匹配的內容。

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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM