【问题标题】:Find number of replacements when using a global Regular Expression使用全局正则表达式时查找替换数
【发布时间】:2017-12-09 09:42:59
【问题描述】:

我有一个包含单词的句子(字符串)。我想用另一个单词替换所有出现的单词。我使用newString = oldString.replace(/w1/gi, w2);,但现在我需要向用户报告我实际替换了多少单词。

有没有一种快速的方法来做到这一点而不诉诸:

  1. 一次替换一个单词并计数。
  2. 逐字比较oldStringnewString 并计算差异? (最简单的情况是,如果 oldString === newString => 0 个替换,但除此之外,我必须同时运行并比较)。

我可以在这里使用任何 RegEx“诡计”,还是应该避免使用 g 标志?

【问题讨论】:

  • 使用回调var cnt=0; var res = s.replace(/str/g, function($0) { cnt++; return 'newstr';});

标签: javascript regex string


【解决方案1】:

选项 1:使用 replace 回调

通过使用回调,你可以增加一个计数器,然后在回调中返回新单词,这样你就可以只遍历字符串1次,达到一个计数。

var string = 'Hello, hello, hello, this is so awesome';
var count = 0;
string = string.replace(/hello/gi, function() {
  count++;
  return 'hi';
});

console.log('New string:', string);
console.log('Words replaced', count);

选项 2:使用split join

同样使用 split 方法,而不是使用正则表达式,只需加入新单词即可创建新字符串。此解决方案可让您完全避免使用正则表达式来实现计数。

var string = 'Hello, hello, hello, this is so awesome';

string = string.split(/hello/i);
var count = string.length - 1;
string = string.join('Hi');

console.log('New string:', string);
console.log('Words replaced', count);

【讨论】:

  • 是的!替换函数参数是我需要的!谢谢!
【解决方案2】:

您可以使用您正在使用的正则表达式拆分字符串并获取长度。

oldString.split(/w1/gi).length - 1

工作示例:

var string = "The is the of the and the";
var newString = string.replace(/the/gi, "hello");

var wordsReplaced = string.split(/the/gi).length - 1;

console.log("Words replaced: ", wordsReplaced);

【讨论】:

  • 谢谢你 - 它会工作的!我希望有一种更有效的方法,然后重新遍历原始字符串。如果我们找不到 - 您的答案将起作用。
猜你喜欢
  • 1970-01-01
  • 2012-06-06
  • 2023-03-21
  • 2014-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多