Advertisement
DooMxDD

[JS][Func] Replace word in sentence w/ preserved capitals

Mar 22nd, 2017
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function replaceWord(str, before, after)
  2. {
  3.   var re = new RegExp(before, 'gi');
  4.   after = (before[0].toUpperCase() == before[0] ? after = after[0].toUpperCase() + after.slice(1) : after);//if first letter of before is capitalized, it'll change after to capitalized as well.
  5.   str = str.replace(re, after);
  6.   return str;
  7. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement