2017-10-19 110 views
0

我们有一个Google脚本作为附件运行,并将基本格式转换为基本HTML。查看Google文档的网址

但是,我似乎无法检测链接时,他们是一个完整的句子。

应该找到链接的函数;

function processText(item, output) { 
var text = item.getText(); 
var indices = item.getTextAttributeIndices(); 

Logger.log("processText. "+item+". "+text); 

if (indices.length <= 1) { 
    var partAtts = item.getAttributes(indices[0]); 

// Assuming that a whole para fully italic is a quote 
if(item.isBold()) { 
    output.push('<b>' + text + '</b>'); 
} 
else if(item.isItalic()) { 
    output.push('<blockquote>' + text + '</blockquote>'); 
} 
else if (text.trim().indexOf('http://') > -1) { 
    output.push('<a href="' + text + '" rel="nofollow" class="a">' + text + '</a>'); 
} 
else if (text.trim().indexOf('https://') > -1) { 
    output.push('<a href="' + text + '" rel="nofollow" class="b">' + text + '</a>'); 
} 
else { 
//using this to debug as have no idea how to run from script and use Logger. 
    output.push(partAtts[0]+"<<< "+text.trim().indexOf('http://')+ ", "+ text.trim().indexOf('https://')+ " (pt) "+text+". "+indices); 
    //output.push(text); 
} 
} 
else { 
... 

输出 -

<p>A sentence with a <a href="https://www.theguardian.com/politics/2017/oct/19/brexit-talks-uk-must-prepare-to-leave-without-deal-say-former-ministers" class="c">link</a></p> 
<p>undefined<<< -1, -1 (pt) A full link sentence. 0</p> 

这就是文字看起来像在谷歌文档。

enter image description here

赞赏任何帮助。这里真的超出我的深度。即使它只是为了帮助我从脚本编辑器中运行它。即选择一个文档,这样我就可以看到日志输出并增加我的试验和错误输出!

回答

1

我不明白你的脚本的逻辑;它为URL和链接文本使用相同的“文本”变量。 Google文档在文本内容中不应该有像http://这样的裸链接;链接被编码为其他文本属性,并通过getLinkUrl进行访问。

这是我的函数,通过所有文本元素,检测链接,并返回HTML格式。请注意,一个文本元素可能包含多个链接。我的测试用例是

一句linkanother link以及更多文字。

A full link sentence

并且输出是

A sentence with a <a href="http://example.com">link</a> and <a href="https://stackoverflow.com">another link</a> and more text. 
<a href="http://example.com">A full link sentence</a> 

的while循环越过文本元素;那么for循环会遍历文本属性索引。 textPart是两个索引之间的文本的一部分; url是这个部分链接到的任何东西(如果它不是链接,可能是null)。每个部分被推送到数组output,适用时使用链接格式。该数组已加入并记录。

function linkDetection() { 
    var body = DocumentApp.getActiveDocument().getBody(); 
    var found = body.findElement(DocumentApp.ElementType.TEXT); 
    while (found) { 
    var elem = found.getElement(); 
    var text = elem.getText(); 
    var output = []; 
    var indices = elem.getTextAttributeIndices(); 
    for (var i = 0; i < indices.length; i++) { 
     var textPart = (i == indices.length - 1 ? text.slice(indices[i]) : text.slice(indices[i], indices[i+1]));  
     var url = elem.getLinkUrl(indices[i]); 
     output.push(url ? '<a href="' + url + '">' + textPart + '</a>' : textPart); 
    } 
    Logger.log(output.join('')); 
    found = body.findElement(DocumentApp.ElementType.TEXT, found); 
    } 
}