这是Google应用脚本中的错误吗?

时间:2017-10-26 17:06:03

标签: regex google-apps-script google-docs

我正在使用Google Applied Digital Skills网站上的“创建编辑工具”项目。当我创建编辑工具时,我遇到了两个故障。一个是“som”这个词突出显示,即使它不在数组中。另一个是突出显示“英雄”这个词。这肯定看起来像一个错误,特别是因为“英雄”突出显示与“英雄”相同的颜色。

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)

    }

1 个答案:

答案 0 :(得分:2)

这不是Apps脚本中的错误。 findText()函数将您正在搜索的字符串(搜索模式)视为正则表达式。在正则表达式中,"。"是一个匹配任何字符的通配符。你有"所以。"和#34;英雄。"在你的搜索模式中,匹配" som"和"英雄"。

你有几个选项,手动逃避。在您的输入数组中:"so\.""hero\.",或使用函数来转义findtext函数中的所有搜索表达式。

这里有一些转义函数的例子:How to escape regular expression in javascript?

值得一提的是,在findText()函数中允许使用正则表达式还有其他优点。例如,您可以避免在数组中以大写/小写形式复制单词。相反,你可以传入一个正则表达式 - "[Vv]ery",它将匹配"非常"或"非常"或者,/very/i完全忽略了案例。请参阅:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp