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:
- Replacing one word at a time and counting.
- Comparing
oldStringtonewStringword-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?
var cnt=0; var res = s.replace(/str/g, function($0) { cnt++; return 'newstr';});