Intermediate Algorithm Scripting: Search and Replace

Challenge -search and replac- ini memiliki 3 argumen :
  • argumen pertama adalah kalimatnya
  • argumen kedua adalah kata yang ingin diganti 
  • argumen ketiga adalah kata penggantinya
 Soal :
function myReplace(str, before, after) {
return str;
}
myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");
 
beberapa catatan :
myReplace("This has a spellngi error", "spellngi", "spelling") should return "This has a spelling error".
myReplace("His name is Tom", "Tom", "john") should return "His name is John".
myReplace("Let us get back to more Coding", "Coding", "algorithms") should return "Let us get back to more Algorithms". 

Hal ini sebenarnya sederhana dan kita dapat menggunakan method .replace() sebagai berikut
str = str.replace(before, after);



Akan tetapi menjadi sedikit lebih kompleks dengan memperharikan huruf besar dan huruf kecil sehingga kita juga akan menggunakan method method berikut
// mengubah ke huruf besar
   var a = kalimat.toUpperCase();
//charAt()
  method yang memberikan balikan karakter tertentu pada sebuah string, contoh :
 str.charAt(index) 
 var anyString = 'Brave new world';
 console.log("The character at index 0   is '" + anyString.charAt(0)   + "'"); // 'B'  
 
Jawab :
function myReplace(str, before, after) {
  // Find index where before is on string
  var index = str.indexOf(before);
  // Check to see if the first letter is uppercase or not
  if (str[index] === str[index].toUpperCase()) {
    // Change the after word to be capitalized before we use it.
    after = after.charAt(0).toUpperCase() + after.slice(1);
  }
  // Now replace the original str with the edited one.
  str = str.replace(before, after);

  return str;
}
 

Comments