user12782994
user12782994

Reputation:

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

So I am currently developing a function to format some input cells on Google Sheets using the app scripts api.

Right now I am taking input from a few cells and formatting them slightly to conform to a manually generated system.

One cell is a school name cell. Sometimes these names tend to be long, I am not super experienced in javascript but right now I am taking an argument from a cell, how would I define that argument's variable so that it would only accept everything in the cell up to the second space.

EX:
Cell A#: Fill-in-the-blank High School Union

Output: Fill-in-the-blank High

/**
*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  
}

Upvotes: 0

Views: 1069

Answers (2)

Cooper
Cooper

Reputation: 64100

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

Upvotes: 0

Barmar
Barmar

Reputation: 781741

Use a regular expression to match everything up to the second space.

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

\S matches non-whitespace characters, \s matches whitespace. So \S*\s*\S* matches non-spaces followed by spaces followed by non-spaces. Then .* matches the rest of the string. The replacement is $1, which is just what was matched by the part inside parentheses.

Upvotes: 2

Related Questions