说我想让以下可重复使用:
function replace_foo(target, replacement) {
return target.replace("string_to_replace",replacement);
}
Run Code Online (Sandbox Code Playgroud)
我可能会这样做:
function replace_foo(target, string_to_replace, replacement) {
return target.replace(string_to_replace,replacement);
}
Run Code Online (Sandbox Code Playgroud)
使用字符串文字这很容易.但是,如果我想让正则表达式变得更加棘手呢?例如,假设我想取代一切,但 string_to_replace.本能地,我会尝试通过以下方式扩展上述内容:
function replace_foo(target, string_to_replace, replacement) {
return target.replace(/^string_to_replace/,replacement);
}
Run Code Online (Sandbox Code Playgroud)
这似乎不起作用.我的猜测是它认为string_to_replace是字符串文字,而不是表示字符串的变量.是否可以使用字符串变量动态创建JavaScript正则表达式?如果可能的话,这样的事情会很棒:
function replace_foo(target, string_to_replace, replacement) {
var regex = "/^" + string_to_replace + "/";
return target.replace(regex,replacement);
}
Run Code Online (Sandbox Code Playgroud) 我想在Google文档中找到一个单词的所有实例并突出显示它们(或评论 - 任何事情都如此突出).我创建了以下函数,但它只找到了单词的第一个外观(在本例中为"the").任何关于如何找到该单词的所有实例的想法将不胜感激!
function findWordsAndHighlight() {
var doc = DocumentApp.openById(Id);
var text = doc.editAsText();
//find word "the"
var result = text.findText("the");
//change background color to yellow
result.getElement().asText().setBackgroundColor(result.getStartOffset(), result.getEndOffsetInclusive(), "#FFFF00");
};
Run Code Online (Sandbox Code Playgroud)