I have a spreadsheet containing a column that looks like this:
1 - Apples
2 - Oranges
3 - Bananas
7 - Pineapples
2 - Oranges
1 - Apples
9 - Cherries
...
I am trying to write a script that trims the first 4 characters from each string leaving only remaining "fruit" substring.
I have a spreadsheet containing a column that looks like this:
1 - Apples
2 - Oranges
3 - Bananas
7 - Pineapples
2 - Oranges
1 - Apples
9 - Cherries
...
I am trying to write a script that trims the first 4 characters from each string leaving only remaining "fruit" substring.
Share edited Dec 26, 2013 at 23:08 Jacobvdb 1,4481 gold badge14 silver badges28 bronze badges asked Dec 26, 2013 at 21:57 user3137859user3137859 351 silver badge6 bronze badges 2- 4 var a ="1 - Apples" var fruit = a.split(" - ")[1] – Jacobvdb Commented Dec 26, 2013 at 23:00
-
If you're sure that it's only 4 characters (as you said)
var fruit = a.substr(4);
is better thansplit
. If not, then this is probably better:fruit = a.substr(a.indexOf('-')+2);
. Becausesplit
will search the whole string and also split dashes (wrapped in spaces) in the names, if you have any. – Henrique G. Abreu Commented Dec 27, 2013 at 11:07
1 Answer
Reset to default 4Try the bellow pice of code. Adapt it to work with spreadsheets.
function myFunction() {
var column = ["1 - Apples",
"2 - Oranges",
"3 - Bananas",
"7 - Pineapples",
"2 - Oranges",
"1 - Apples",
"9 - Cherries"];
for(var x in column) {
column[x] = column[x].substring(4);
//or
//column[x] = column[x].split(" - ")[1]
}
Logger.log(column);
}
live version here.