1

我正在寻找一种解决方案,将输入字符串的每个单词大写为由空格或点分隔的单元格(类似于proper函数)。我知道它坏了,但到目前为止我尝试了什么:

    /*Capitalize Firt Letter of Each Word of input String in Cell*/
  if(activeRow > 1 && activeCol == 3 && ss.getSheetName() == validSheet && activeCell.isBlank() == false)
  { 
    var inputVal = activeCell.getValue().toString();
    Logger.log(inputVal);
    activeCell.setFormulaR1C1("=PROPER("+inputVal+")");
  }

例子:

单元格 A2 的输入:

this tExt neEds to be fixed

单元格 A2 的输出(期望结果):

This Text Needs To Be Fixed

提前致谢

编辑1:我注意到正确的功能不起作用,因为它需要其中的单元格值。

4

1 回答 1

2

Here's a function that takes a string and capitalizes the first letter of each word:

function capitalizePhrase(phrase) {
  var reg = /\b(\w)/g;
  function replace(firstLetters) {
    return firstLetters.toUpperCase();
  }
  capitalized = phrase.replace(reg, replace);
  return capitalized;
}

which you could then use like this:

var inputVal = activeCell.getValue().toString();
var outputVal = capitalizePhrase(inputVal);
activeCell.setValue(outputVal);

Edit - if you also want to set other letters in the word to lower case, you can use this function instead:

function properCase(phrase) {
  var regFirstLetter = /\b(\w)/g;
  var regOtherLetters = /\B(\w)/g;
  function capitalize(firstLetters) {
    return firstLetters.toUpperCase();
  }
  function lowercase(otherLetters) {
    return otherLetters.toLowerCase();
  }
  var capitalized = phrase.replace(regFirstLetter, capitalize);
  var proper = capitalized.replace(regOtherLetters, lowercase);

  return proper;
}
于 2019-03-22T16:08:24.900 回答