簡體   English   中英

在“替換第n個子字符串Google腳本”中向RegEx添加變量

[英]Add variable to RegEx in Replace nth sub-string Google Script

我正在嘗試將變量添加到函數調用中

原始函數來自此處查找並替換字符串中第[bracketed]表達式的第n個出現

var s = "HELLO, WORLD!";
var nth = 0;
s = s.replace(/L/g, function (match, i, original) {
nth++;
return (nth === 2) ? "M" : match;
});
alert(s); // "HELMO, WORLD!";

我正在嘗試這樣做

function ReplaceNth_n() {

Logger.log(ReplaceNth("HELLO, WORLD!", "L", "M"))

}  

function ReplaceNth(strSearch,search_for, replace_with) {
   var nth = 0;
   strSearch = strSearch.replace(/search_for/g, function (match, i, original) {
   nth++;
   return (nth === 2) ? replace_with : match;
   });
  return strSearch 
} 

這部分失敗了; 更換

s = s.replace(/L/g, function (match, i, original)

strSearch = strSearch.replace(/ search_for / g,函數(match,i,original)

我嘗試過變種

strSearch = strSearch.replace('/'+ search_for +'/g', function (match, i, original)

但是沒有怎么做

謝謝

您可以使用new RegExp從變量創建正則表達式。 以下代碼應該工作:

function ReplaceNth_n() {

    Logger.log(ReplaceNth("HELLO, WORLD!", "L", "M"))

}  

function ReplaceNth(strSearch,search_for, replace_with) {
    var nth = 0;
    strSearch = strSearch.replace(new RegExp(search_for, 'g'), function (match, i, original) {
        nth++;
        return (nth === 2) ? replace_with : match;
    });
    return strSearch 
}

ReplaceNth_n() //output 'HELMO, WORLD!'

並且,請正確設置代碼段的格式...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM