如何用Google Apps Script实现员工术语占位符的多格式替换?
解决方案
我们可以通过解析用户输入的单个术语,自动生成所有需要的格式变体,再批量替换文档中的四类占位符。具体实现如下:
1. 核心逻辑拆解
用户输入的是带a/an的小写术语(如an associate),我们从中拆分出冠词和核心名词,然后生成以下四种格式:
- 小写带冠词(对应
<<a/an employee, associate, team member, etc.>>) - 复数形式(对应
<<employees, associates, team members, etc.>>) - 首字母大写单数(对应
<<Employee, Associate, Team member, etc.>>) - 大写冠词+首字母大写名词(对应
<<A/An employee, associate, team member, etc.>>)
2. 完整代码实现
// 解析输入术语,提取冠词和核心名词 function parseTerm(input) { const match = input.match(/^(a|an)\s+(.*)$/i); if (!match) return null; return { article: match[1].toLowerCase(), noun: match[2].trim() }; } // 生成名词复数形式(支持规则和常见不规则复数) function getPlural(noun) { // 可自行扩展不规则复数列表 const irregularPlurals = { "person": "people", "staff": "staff", "team member": "team members" }; if (irregularPlurals[noun]) return irregularPlurals[noun]; // 规则复数转换逻辑 if (noun.match(/(s|x|z|ch|sh)$/i)) return noun + "es"; if (noun.match(/[^aeiou]y$/i)) return noun.slice(0, -1) + "ies"; return noun + "s"; } // 将字符串每个单词首字母大写 function capitalize(str) { return str.split(' ').map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase() ).join(' '); } // 主函数:获取用户输入并替换所有占位符 function empTerm() { const ui = DocumentApp.getUi(); const termResponse = ui.prompt( "员工术语设置", "请输入带a/an的员工术语(小写),例如:'an associate'、'a team member'", ui.ButtonSet.OK_CANCEL ); if (termResponse.getSelectedButton() !== ui.Button.OK) return; const inputTerm = termResponse.getResponseText().trim(); const parsedData = parseTerm(inputTerm); if (!parsedData) { ui.alert("输入格式错误!请按照示例输入,比如'an associate'"); return; } const { article, noun } = parsedData; // 生成所有格式变体 const termVariants = { lowerWithArticle: `${article} ${noun}`, pluralForm: getPlural(noun), capitalizedSingle: capitalize(noun), capitalizedWithArticle: `${article.charAt(0).toUpperCase() + article.slice(1)} ${capitalize(noun)}` }; const docBody = DocumentApp.getActiveDocument().getBody(); // 批量替换四类占位符 docBody.replaceText("<<a/an employee, associate, team member, etc.>>", termVariants.lowerWithArticle); docBody.replaceText("<<employees, associates, team members, etc.>>", termVariants.pluralForm); docBody.replaceText("<<Employee, Associate, Team member, etc.>>", termVariants.capitalizedSingle); docBody.replaceText("<<A/An employee, associate, team member, etc.>>", termVariants.capitalizedWithArticle); ui.alert("术语替换完成!"); }
3. 使用说明
- 运行
empTerm函数后,按提示输入符合格式的术语(如a team member) - 脚本会自动校验输入格式,不符合要求会弹出提示
- 复数转换支持常见规则和自定义不规则复数,可根据实际需求扩展
irregularPlurals对象
内容的提问来源于stack exchange,提问作者Craig
相关产品推荐
相关产品推荐

