string - 带有样式的 Google 脚本字符串
问题描述
我对 Google Script 中如何处理字符串感到很困惑。特别是,似乎可以设置字符串样式,但我不知道如何实际执行此操作。
例如:我创建一个 Google 表单,添加一个短文本问题,然后复制粘贴此处生成的粗体文本:https ://lingojam.com/BoldTextGenerator
如果我用脚本打开这个表单,我可以用
var form = FormApp.openById(formID);
var Items = form.getItems();
var test = Items[0].getTitle();
这个“test”变量是一个字符串(我用 Logger.log(typeof(test)) 进行了检查),不是“Text”也不是“RichText”,并且诸如 .isBold() 之类的方法将不起作用。
但是,Logger.log(test) 确实在日志日志中输出粗体文本 - 因此该字符串确实包含有关其样式的一些信息。
然而,我似乎无法在 Google Script 中定义样式字符串。我尝试了完全不同的东西,但没有一个奏效
var dummy = "Hello World !"
Logger.log(dummy.bold())
Logger.log(dummy.setBold(true))
Logger.log(dummy.setFontWeight("bold"))
Logger.log("<b>"+dummy+"</b>")
Logger.log("**"+dummy+"**")
我该怎么做才能让我的虚拟字符串以粗体字体记录(我的真正目标是使用 .setTitle(dummy) 方法来获得粗体字体表单项)?
解决方案
我相信你的目标如下。
- 您想使用 Google Apps 脚本将粗体文本设置为 Google 表单上项目的标题。
问题和解决方法:
遗憾的是,在现阶段,Google Form 服务中还没有直接管理富文本到 Google Form 上每个项目的标题的方法。但是当将加粗的文字直接复制粘贴到Google Form上的item的标题上就可以了。因此,在这个答案中,作为当前的解决方法,我想建议将文本数据转换为带有 unicode 的粗体类型的文本,并将转换后的文本放入 Google 表单。
此解决方法的流程如下。
- 使用 unicode 将文本转换为粗体。
- 在此转换中,文本中的每个字符都使用原始字符代码和粗体字符代码之间的差异转换为粗体类型。
- 将转换后的文本放到 Google 表单上的项目标题中。
当上述流程反映到脚本时,它变成如下。
示例脚本:
function myFunction() {
// 1. Convert the text to the bold type with the unicode.
const conv = {
c: function(text, obj) {return text.replace(new RegExp(`[${obj.reduce((s, {r}) => s += r, "")}]`, "g"), e => {
const t = e.codePointAt(0);
if ((t >= 48 && t <= 57) || (t >= 65 && t <= 90) || (t >= 97 && t <= 122)) {
return obj.reduce((s, {r, d}) => {
if (new RegExp(`[${r}]`).test(e)) s = String.fromCodePoint(e.codePointAt(0) + d);
return s;
}, "")
}
return e;
})},
bold: function(text) {return this.c(text, [{r: "0-9", d: 120734}, {r: "A-Z", d: 120211}, {r: "a-z", d: 120205}])},
italic: function(text) {return this.c(text, [{r: "A-Z", d: 120263}, {r: "a-z", d: 120257}])},
boldItalic: function(text) {return this.c(text, [{r: "A-Z", d: 120315}, {r: "a-z", d: 120309}])},
};
var newTitle = "New title for item 1";
var convertedNewTitle = conv.bold(newTitle); // Bold type
// var convertedNewTitle = conv.italic(newTitle); // Italic type
// var convertedNewTitle = conv.boldItalic(newTitle); // Bold-italic type
// 2. Put to the converted text to the title of item on Google Form.
var formID = "###"; // Please set the Form ID.
var form = FormApp.openById(formID);
var Items = form.getItems();
Items[0].setTitle(convertedNewTitle);
}
- 在这个示例脚本中,可以转换粗体、斜体和粗斜体类型。
- 在这种情况下,数字和特定字符没有粗体、斜体和粗斜体类型。请注意这一点。
结果:
使用上述示例脚本时,将获得以下结果。
从: 至:测试
https://jsfiddle.net/7bL5r3em/
参考:
推荐阅读
- python - 如何强制 Pygame 2.0.0 使用最新版本的 SDL?
- javascript - JS中的Bigint破坏了数组排序?
- android - 在视图变得不可见后执行任务
- exchange-server - Exchange 2013 与会者响应始终为空
- python - 卡夫卡消费者无法阅读新的味精?
- mysql - WP_查询 | 数组序列化形式的 meta_query 参数元值
- ios - Xcode 12. 将 swift 标准库复制到...错误
- grapesjs - 我如何在grapesjs中设置表单样式?
- java - 运行时在eclipse中找不到主类
- c# - MicrosoftConfigurationBuilders 连接字符串提供程序名称错误(C#、Oracle)