【问题标题】:Add parameter to String#replace将参数添加到字符串#replace
【发布时间】:2018-08-27 22:02:08
【问题描述】:

如果它是管道,我想从字符串中删除最后一个字符。我有

.replace(/\|(\s+)?$/, '')

我想添加一个参数delim 来替换,因为最后一个字符发生了变化。我正在尝试:

.replace(/\+delim +(\s+)?$/, '')

但没有运气。

使用该函数的代码:

 rangeValues[cellRow][hn[j]] = rangeValues[cellRow][hn[j]].toString()
     .split(frValues[i][0])
     .join(frValues[i][1]).trim()
     .replace(/\ + delim + (\s+)?$/, '');

【问题讨论】:

  • 分隔符的“更改”未知?也许你可以在正则表达式的 () 内做一些条件。

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


【解决方案1】:
  • 您想使用正则表达式删除最后一个字符。
  • 您想通过更改正则表达式中的delim 来使用。

如果我对你的问题的理解是正确的,那么使用 RegExp 怎么样?

修改脚本:

var delim = "|";
var string = "\\" + delim + "(\\s+)?$";
var regex = new RegExp(string);

rangeValues[cellRow][hn[j]] = rangeValues[cellRow][hn[j]].toString()
     .split(frValues[i][0])
     .join(frValues[i][1]).trim()
     .replace(regex, '');

注意:

  • 当delim 为| 时,regex 变为/\|(\s+)?$/。

参考:

如果我误解了你的问题,我很抱歉。

【讨论】:

  • @Einarr 很高兴您的问题得到了解决。也谢谢你!
猜你喜欢
  • 2019-05-13
  • 1970-01-01
  • 1970-01-01
  • 2011-02-11
  • 2012-12-20
  • 2012-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多