24 Ocak 2014 Cuma

Javascript replaceAll() metodunun yazılması

JavaScript'te kullandığımız replace methodu bir string'de sadece bulduğu ilk eşleşmeyi değiştiriyor. Yani string içerisindeki tüm eşleşen kayıtlar üzerinde bir değişiklik yapmıyor. Tüm string içerisinde değiştirme yapmak için iki method önerilmektedir.
 
Birincisi aramayı Regex kullanarak yapıp, Regex'in ikinci parametresi olarak g (Global) geçmek. Böylece tüm string dizisi içerisinde aradığından bu sorun ortadan kalkıyor. 
Örnek method:
 
function replaceAll(txt, replace, with_this) {
  return txt.replace(new RegExp(replace, 'g'),with_this);

}
 
 
İkincisi ise JavaScript'in string kütüphanesi içerisine kendi replaceAll methodumuzu eklememiz. 
Örnek method:
 
// Replaces all instances of the given substring.
String.prototype.replaceAll = function(

    strTarget,        // The substring you want to replace

    strSubString    // The string you want to replace in.

  ){
 
    var strText = this;
    var intIndexOfMatch = strText.indexOf( strTarget );

 

    // Keep looping while an instance of the target string

    // still exists in the string.

    while (intIndexOfMatch != -1){

        // Relace out the current instance.

        strText = strText.replace( strTarget, strSubString )

         

        // Get the index of any next matching substring.

        intIndexOfMatch = strText.indexOf( strTarget );

    }

     

    // Return the updated string with ALL the target strings

    // replaced out with the new substring.

    return( strText );

}
 
Benim fikrime göre ikincisi kullanmak daha mantıklı çünkü Regex ile yapılacak aramalarda ilk göndereceğimiz parametreyi Regex'in anlayacağı şekilde yollamamız gerektiği için (örneğin "." yollamak için "\." yollamamız gerekli gibi) hem gözden kaçabilir, hem de zorlayıcı olabilir.
 
Kaynaklar:

Hiç yorum yok:

Yorum Gönder