1

I have a sentence (string) containing words. I want to replace all occurrences of a word with another. I use newString = oldString.replace(/w1/gi, w2);, but now I need to report to the user how many words I actually replaced.

Is there a quick way to do it without resorting to:

  1. Replacing one word at a time and counting.
  2. Comparing oldString to newString word-by-word and tallying the differences? (The easy case is if oldString === newString => 0 replacements, but beyond that, I'll have to run over both and compare).

Is there any RegEx "trickery" I can use here, or should I just avoid using the g flag?

1
  • 1
    Use a callback var cnt=0; var res = s.replace(/str/g, function($0) { cnt++; return 'newstr';}); Commented Jul 5, 2017 at 17:09

2 Answers 2

3

Option 1: Using the replace callback

By using the callback, you can increment a counter, and then return the new word in the callback, this allows you to traverse the string only 1 time, and achieve a count.

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);

Option 2: Using split and join

Also using the split method, instead of using regex, just join with the new word to create the new string. This solution allows you to avoid using regex at all to achieve counts.

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);

Sign up to request clarification or add additional context in comments.

1 Comment

Yes! The replace function parameter was what I needed! Thanks!
2

You could split the string with the regex you're using and get the length.

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

Working example:

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);

1 Comment

Thanks for this - it would work! I'm hoping there's a more efficient way then re-traversing the original string though. If we can't find one - your answer will serve.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.