Advertisement
Guest User

Untitled

a guest
Jun 26th, 2017
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.30 KB | None | 0 0
  1. function myReplace(str, before, after) {
  2.  
  3. // create a function that will change the casing of any number of letter in parameter "target"
  4. // matching parameter "source"
  5. function applyCasing(source, target) {
  6. // split the source and target strings to array of letters
  7. var targetArr = target.split("");
  8. var sourceArr = source.split("");
  9. // iterate through all the items of sourceArr and targetArr arrays till loop hits the end of shortest array
  10. for (var i = 0; i < Math.min(targetArr.length, sourceArr.length); i++){
  11. // find out the casing of every letter from sourceArr using regular expression
  12. // if sourceArr[i] is upper case then convert targetArr[i] to upper case
  13. if (/[A-Z]/.test(sourceArr[i])) {
  14. targetArr[i] = targetArr[i].toUpperCase();
  15. }
  16. // if sourceArr[i] is not upper case then convert targetArr[i] to lower case
  17. else targetArr[i] = targetArr[i].toLowerCase();
  18. }
  19. // join modified targetArr to string and return
  20. return (targetArr.join(""));
  21. }
  22.  
  23.  
  24. // replace "before" with "after" with "before"-casing
  25. return str.replace(before, applyCasing(before, after));
  26. }
  27.  
  28. // test here
  29. myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement