What I'm trying to do is write a function to replace one word in a given sentence. One of the requirements is that the case of the replaced word will be saved as with the original.
I wrote the following function:
function replace(str, before, after) { var re = new RegExp('(\\.*)?(' + before + ')(\\.*)?', 'i'); return str.replace(re, after); }
Everything works fine, except that the case of the word after does not match the word before .
INFO:
I solved the same problem using arrays (using split() , splice() , indexOf() ) and replacing only the before element with non-dynamic RegExp() , and this case has been saved. That’s why I don’t quite understand why my other solution is not working.
source share