2017-10-19 4 views
0

のGoogleドキュメントのテキストを確認してください。たちはアドオンとして動作し、基本的なHTMLに基本的な書式を変換し、Googleのスクリプトを持っているURL

しかし、完全な文章の場合、リンクを検出できないようです。リンクを見つける必要があります

機能。

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> 

これは、テキストは、Googleドキュメントのように見えるものです。

enter image description here

すべてのヘルプ高く評価しました。本当にここの私の深さから。場合でも、私はスクリプトエディタからこれを実行するのに役立ちます。私はログ出力を見ることができ、私の試行錯誤の出力を増やすことができるように文書を選ぶ!

答えて

1

私はあなたのスクリプトのロジックを理解していません。 URLとリンクテキストに同じ "text"変数を使用します。 Googleドキュメントはテキストコンテンツにhttp://のような裸のリンクを持っているとは考えられません。リンクは他のテキスト属性として符号化され、getLinkUrlでアクセスされます。

すべてのテキスト要素を調べ、リンクを検出し、HTML形式を返す関数です。 1つのテキストエレメントには複数のリンクが含まれることがあります。テストケースは

linkと以上の文です。

A full link sentence

出力はwhileループは、テキスト要素を乗り越え

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> 

あります。 for-loopはテキスト属性インデックスを上書きします。 textPartは、2つのインデックス間のテキストの一部です。 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); 
    } 
} 
関連する問題