我需要在分隔字符串中,仅当子字符串与替换值匹配时才替换分隔符之间的子字符串
在 Google 表格中使用它
配套的
var ifind = ["AA", "CaaL"];
var ireplace = ["zz", "Bob"];
zz replaces AA
Bob replaces CaaL
我有
| Id | Segment |
|----|--------------------|
| 1 | AAA AA|AA|CaaL AA |
| 2 | AAA-AA|AA|CaaL |
| 3 | AAA, AA|AA|AA |
| 4 | AA |
| 5 | AA AA |
| 6 | AA, AA |
| 7 | |
| 8 | CaaL |
| 9 | AA |
我需要
| Id | Segment |
|----|-------------------|
| 1 | AAA AA|zz|CaaL AA |
| 2 | AAA-AA|zz|Bob |
| 3 | AAA, AA|zz|zz |
| 4 | zz |
| 5 | AA AA |
| 6 | AA, AA |
| 7 | |
| 8 | Bob |
| 9 | zz |
我已经尝试过(除其他外)
return [iFinds.reduce((str, k) => str.replace(new RegExp('\\b'+k+'\\b','g'),map[k]), input[0])];
and
return [iFinds.reduce((str, k) => str.replace(new RegExp('(?![ .,]|^)?(\\b' + k + '\\b)(?=[., ]|$)','g'),map[k]), input[0])];
and
return [iFinds.reduce((str, k) => str.split(k).join (map[k]), input[0])];
我的功能(来自这里)
function findReplace_mod1() {
const ss = SpreadsheetApp.getActiveSheet();
const col = ss.getRange(2, 3, ss.getLastRow()).getValues();
var ifind = ["AA", "Caal"];
var ireplace = ["zz", "Bob"];
var map = {};
ifind.forEach(function(item, i) {
map[item] = ireplace[i];
});
//const map = { Fellow: 'AAA', bob: 'BBB' };
const iFinds = Object.keys(map);
ss.getRange(2, 3, ss.getLastRow()).setValues(col.map(fr));
function fr(input) {
return [iFinds.reduce((str, k) => str.replace(k, map[k]), input[0])];
}
}
谢谢
慕标5832272
三国纷争
相关分类