2017-10-26 4 views
-1

Google Applied Digital Skillsのウェブサイトの「編集ツールの作成」プロジェクトに取り組んでいました。編集ツールを作成していたとき、私は2つの不具合に遭遇しました。 1つは、単語 "som"が強調表示されているということです。もう一つは、「英雄」という言葉が強調表示されていることです。これは間違いなくバグのように見えます。なぜなら、 "ヒーロー"は "ヒーロー"と同じ色で強調表示されているからです。これは私が作ったエラーである場合これはGoogle Appsスクリプトのバグですか?

Screenshot of Document

は誰もが知っていますかそれはグリッチですか?ここ はコードです:

function findText(item) { 

     //choose a random color as the background 

     //credit to James from https://stackoverflow.com/questions/1484506/random-color-generator 

     var background = '#' + (Math.random().toString(16) + "000000").substring(2, 8) 

     //log the item being found to make sure it is being searched for 

     Logger.log(item) 

     //shows the computer what the search result is 

     var searchResult 

     //find the search result 

     searchResult = DocumentApp.getActiveDocument().getBody().findText(item) 

     //put it in the log 

     Logger.log(searchResult) 

     //loop until item is no longer found 

     while (searchResult !== null) { 

      //change the background color for a set space, which is when item is first used. 

      searchResult.getElement().asText().setBackgroundColor(searchResult.getStartOffset(), searchResult.getEndOffsetInclusive(), background) 

      //find the text again 

      searchResult = DocumentApp.getActiveDocument().getBody().findText(item, searchResult) 

      //end of the loop 

     } 



    } 

    function highlightProblem() { 

     //array showing all values of item 

     var words = ["very", "Very", "totally", "Totally", "heroic", "Heroic", "really", "Really", "so ", "so. ", "so, ", "So ", "So. ", "So, ", "its", "Its", "good", "Good", "examples", "Examples", "hero ", "hero. ", "hero, ", "Hero ", "Hero. ", "Hero, "] 

     //find each item in the array 

     words.forEach(findText) 

    } 

答えて

2

これは、Appsスクリプトのバグではありません。 findText()関数は、検索している文字列(検索パターン)を正規表現として扱います。正規表現では、 "。"任意の文字に一致するワイルドカードです。あなたは「そうです。」と "英雄"。あなたの検索パターンでは、 "som"と "heroi"と一致します。

いくつかのオプションがありますが、手動でエスケープしてください。あなたの入力配列に:"so\.""hero\."、またはfindtext関数内のすべての検索式をエスケープする関数を使用してください。

は、ここでは、エスケープ関数の例があります:How to escape regular expression in javascript?

それはあなたのFINDTEXT()関数での正規表現の使用を可能にする他の利点がある言及する価値があります。たとえば、配列内の大文字/小文字の単語を重複させることを避けることができます。代わりに、 "Very"または "very"に一致する単一の正規表現"[Vv]ery"を渡すか、大文字小文字を完全に無視する/very/iに渡すことができます。参照:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp

関連する問題