Google Docs脚本将选择转换为超链接

发布于 2025-01-19 16:28:42 字数 1022 浏览 0 评论 0原文

我是 Google Apps 脚本的新手,过去只接触过一点 JS。

我觉得这应该很简单,但找不到答案——也许太明显了!

我希望用户能够在文档中选择文本(在本例中是名称)。然后,脚本会将所选文本转换为链接。

例如 在文档中突出显示“John Smith” 这变成了一个超链接,网址为“https://naming.com/john-smith”

我以前将其作为 MS Word 宏使用,并希望转换为 Google:

Sub LinkName()
Dim Name As String

With Selection

.MoveStartWhile Cset:=" ", Count:=wdForward
.MoveEndWhile Cset:=Chr(13), Count:=wdBackward
.MoveEndWhile Cset:=" ", Count:=wdBackward

End With

Name = LCase(Selection.Text)
Name = Replace(Name, " ", "-")
If Name = "jonny-smith" Then Name = "john-smith"
If Name = "johnathan-smith" Then Name = "john-smith"

ActiveDocument.Hyperlinks.Add Anchor:=Selection.Range, _
 Address:="https://naming.com/" & Name
 
End Sub

不幸的是,我什至无法获取以下内容在开始研究如何将选定的文本转换为 slug 作为变量之前!

function linkName () {
 
DocumentApp.getActiveDocument()
.getSelection()
.editAsText()
.setLinkUrl(0,0,"https://naming.com/john-smith");

DocumentApp.getUi().alert("Link added")

}

任何帮助将不胜感激!

干杯

I'm new to Google Apps Script and have only done a little JS in the past.

I feel like this should be simple, but can't find an answer – maybe it's too obvious!

I would like users to be able to select text, in this case a name, in the document. The script would then turn this selected text into a link.

E.g.
Highlight 'John Smith' in the document
This becomes a hyperlink with the url as 'https://naming.com/john-smith'

I previously had this working as an MS Word Macro and would like to convert to Google:

Sub LinkName()
Dim Name As String

With Selection

.MoveStartWhile Cset:=" ", Count:=wdForward
.MoveEndWhile Cset:=Chr(13), Count:=wdBackward
.MoveEndWhile Cset:=" ", Count:=wdBackward

End With

Name = LCase(Selection.Text)
Name = Replace(Name, " ", "-")
If Name = "jonny-smith" Then Name = "john-smith"
If Name = "johnathan-smith" Then Name = "john-smith"

ActiveDocument.Hyperlinks.Add Anchor:=Selection.Range, _
 Address:="https://naming.com/" & Name
 
End Sub

Unfortunately, I can't even get the following to work before starting to look at how to convert the selected text to a slug as a variable!

function linkName () {
 
DocumentApp.getActiveDocument()
.getSelection()
.editAsText()
.setLinkUrl(0,0,"https://naming.com/john-smith");

DocumentApp.getUi().alert("Link added")

}

Any help would be much appreciated!

Cheers

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

痴意少年 2025-01-26 16:28:42

基本上可以这样做:

function linkName() {

  var selection = DocumentApp
    .getActiveDocument()
    .getSelection()
    .getRangeElements()[0];

  var start = selection.getStartOffset();
  var end   = selection.getEndOffsetInclusive();
  var url   = 'https://naming.com/john-smith';

  selection
    .getElement()
    .editAsText()
    .setLinkUrl(start, end, url);

  DocumentApp.getUi().alert("Link added");
}

但是还有另一个问题:您应该如何运行此脚本?我认为,从脚本编辑器运行它并不是最方便的方法。可能需要将功能添加到自定义菜单或其他内容中。

Basically it can be done this way:

function linkName() {

  var selection = DocumentApp
    .getActiveDocument()
    .getSelection()
    .getRangeElements()[0];

  var start = selection.getStartOffset();
  var end   = selection.getEndOffsetInclusive();
  var url   = 'https://naming.com/john-smith';

  selection
    .getElement()
    .editAsText()
    .setLinkUrl(start, end, url);

  DocumentApp.getUi().alert("Link added");
}

But there is another question: how do you suppose to run this script? It's not exactly most convenient way to run it from Script Editor, I think. Probably it's need to add the function to the custom menu or something.

遮云壑 2025-01-26 16:28:42

感谢@Yuri,我到达了我需要去的地方!

下面是代码,也是从这里借用的: https://stackoverflow.com/questions/16639331/get -user-selected-text

并从这里开始:https://gist.github.com/codeguy/6684588

    function onOpen() {
  DocumentApp.getUi().createMenu('Names')
    .addItem("Link Athlete", 'linkName' )
    .addToUi();
}

function linkName () {
 

  var selection = DocumentApp
    .getActiveDocument()
    .getSelection()
    .getRangeElements()[0];

  var start = selection.getStartOffset();
  var end   = selection.getEndOffsetInclusive();

var elements = DocumentApp.getActiveDocument().getSelection().getSelectedElements();
if(elements.length > 1){
}
else {
var element = elements[0].getElement();
      var startOffset = elements[0].getStartOffset();      // -1 if whole element
      var endOffset = elements[0].getEndOffsetInclusive(); // -1 if whole element
      var selectedText = element.asText().getText();       // All text from element
      // Is only part of the element selected?
      if (elements[0].isPartial())
        selectedText = selectedText.substring(startOffset,endOffset+1);

      // Google Doc UI "word selection" (double click)
      // selects trailing spaces - trim them
      selectedText = selectedText.trim();
      endOffset = startOffset + selectedText.length - 1;

selectedText = selectedText
    .toString()                           // Cast to string (optional)
    .normalize('NFKD')            // The normalize() using NFKD method returns the Unicode Normalization Form of a given string.
    .toLowerCase()                  // Convert the string to lowercase letters
    .trim()                                  // Remove whitespace from both sides of a string (optional)
    .replace(/\s+/g, '-')            // Replace spaces with -
    .replace(/[^\w\-]+/g, '')     // Remove all non-word chars
    .replace(/\-\-+/g, '-');        // Replace multiple - with single -

}

if (selectedText == "jonny-smith") {
selectedText = "john-smith"
}
if (selectedText == "johnathan-smith") {
selectedText = "john-smith"
}


  var url   = 'https://naming.com/' + selectedText;

  selection
    .getElement()
    .editAsText()
    .setLinkUrl(start, end, url);

/*
  DocumentApp.getUi().alert("Link added");
  DocumentApp.getUi().alert(selectedText);
  */
}

我确信有更干净的方法,但它有效!

Thanks to @Yuri, I got to where I needed to be!

Below is the code, which also borrows from here: https://stackoverflow.com/questions/16639331/get-user-selected-text

and from here: https://gist.github.com/codeguy/6684588

    function onOpen() {
  DocumentApp.getUi().createMenu('Names')
    .addItem("Link Athlete", 'linkName' )
    .addToUi();
}

function linkName () {
 

  var selection = DocumentApp
    .getActiveDocument()
    .getSelection()
    .getRangeElements()[0];

  var start = selection.getStartOffset();
  var end   = selection.getEndOffsetInclusive();

var elements = DocumentApp.getActiveDocument().getSelection().getSelectedElements();
if(elements.length > 1){
}
else {
var element = elements[0].getElement();
      var startOffset = elements[0].getStartOffset();      // -1 if whole element
      var endOffset = elements[0].getEndOffsetInclusive(); // -1 if whole element
      var selectedText = element.asText().getText();       // All text from element
      // Is only part of the element selected?
      if (elements[0].isPartial())
        selectedText = selectedText.substring(startOffset,endOffset+1);

      // Google Doc UI "word selection" (double click)
      // selects trailing spaces - trim them
      selectedText = selectedText.trim();
      endOffset = startOffset + selectedText.length - 1;

selectedText = selectedText
    .toString()                           // Cast to string (optional)
    .normalize('NFKD')            // The normalize() using NFKD method returns the Unicode Normalization Form of a given string.
    .toLowerCase()                  // Convert the string to lowercase letters
    .trim()                                  // Remove whitespace from both sides of a string (optional)
    .replace(/\s+/g, '-')            // Replace spaces with -
    .replace(/[^\w\-]+/g, '')     // Remove all non-word chars
    .replace(/\-\-+/g, '-');        // Replace multiple - with single -

}

if (selectedText == "jonny-smith") {
selectedText = "john-smith"
}
if (selectedText == "johnathan-smith") {
selectedText = "john-smith"
}


  var url   = 'https://naming.com/' + selectedText;

  selection
    .getElement()
    .editAsText()
    .setLinkUrl(start, end, url);

/*
  DocumentApp.getUi().alert("Link added");
  DocumentApp.getUi().alert(selectedText);
  */
}

I'm sure there are cleaner ways, but it's working!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文