我试图操作字段的富文本值。
我可以获得一个单元格的丰富文本值,我可以获得运行,我可以更新链接,但我不知道如何删除链接或操纵部分运行。使用此单元格作为示例:
“紧急”一词,包括前面和后面的一些空格,是一个链接。我想保留链接和空格,但我想从空格中删除链接。
var richTextValue = range.getRichTextValue();
var newRichTextValue = richTextValue.copy();
// get all the runs
richTextValue.getRuns().forEach(run => {
// we only need runs that are links
if (run.getLinkUrl()) {
// get the run text
var text = run.getText();
// if the text of this run starts with spaces
if (hasLeadingSpaces = text.match(/^\s+/)) {
var numSpaces = hasLeadingSpaces[0].length;
// now what?
}
}
});
我知道空格从哪里开始和结束,但似乎没有一种方法来设置运行的文本或RichTextValue的一部分。
RichTextValueBuilder
,然后设置整个文本,然后将链接添加到相关部分,但是如何将该RichTextValueBuilder
保存回整体呢?发布于 2022-05-03 19:16:01
对于这种特殊情况,我可以提出以下代码:
function myFunction() {
var range = SpreadsheetApp.getActiveSheet().getRange('a1');
var richTextValue = range.getRichTextValue();
var all_text = richTextValue.getText();
var runs = richTextValue.getRuns();
var link = runs.filter(r => r.getLinkUrl())[0]; // a first link from the cell
var link_url = link.getLinkUrl();
var link_text = link.getText().trim();
var link_style = link.getTextStyle();
all_text = all_text.replace(/\s+/g, ' '); // hope the extra spaces are only around link
var start = all_text.indexOf(link_text); // hope the text is unique
var end = start + link_text.length;
const newRichTextValue = SpreadsheetApp.newRichTextValue()
.setText(all_text)
.setLinkUrl(start, end, link_url)
.setTextStyle(start, end, link_style)
.build();
range.clear().setRichTextValue(newRichTextValue);
}
但这可能不是一个普遍的解决方案。例如,它不会将文本的文本样式保留在链接周围。等。
https://stackoverflow.com/questions/72102901
复制相似问题