最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Google Spreadsheet Script Trim First X Characters Each Cell in Range - Stack Overflow

programmeradmin5浏览0评论

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 than split. If not, then this is probably better: fruit = a.substr(a.indexOf('-')+2);. Because split 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
Add a ment  | 

1 Answer 1

Reset to default 4

Try 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.

发布评论

评论列表(0)

  1. 暂无评论