shabashj
2/15/2016 - 1:35 PM

replace at index and replace between indexes

replace at index and replace between indexes

String.prototype.replaceBetween = function(start, end, what) {
    return this.substring(0, start) + what + this.substring(end);
};

String.prototype.replaceAt=function(index, character) {
    return this.substr(0, index) + character + this.substr(index+character.length);
}

var str0 = "asdaksj {\"asdasdasd>adasd\"}";
var str1 = "asdaksj \"asdasdasd>adasd\"}";
var str2 = "asdaksj {\"asdasdasd>adasd\"";
var str3 = "asdaksj \"asdasdasd>adasd\"";
var str4 = "asdaksj {\"asdasdasd>adasd\"} sfhgfj {\"Yeyeyey>yeyeyey\"} blbalbalbalb"; 
var str5 = "asdaksj {\"asdasdasd>adasd\"} sfhgfj {\"Yeyeyey>yeyeyey\" blbalbalbalb"; 
var str6 = "Hello \"Do>not replace\"} but here {\"yes>replace\"} and {\"here>again no, bye"; 

function replaceGreaterThen(str){
    var iOpenIndex = -1, iCloseIndex = -1, iMatchIndex = -1, iStartPosition = 0;

    while(iStartPosition > -1){
        if( (iOpenIndex = str.indexOf("{", iStartPosition)) === -1){
            break;            
        }        
        if( (iCloseIndex = str.indexOf("}", iOpenIndex)) === -1){
            break;            
        }

        iMatchIndex = str.indexOf(">", iOpenIndex)    

        if(iMatchIndex>-1 && iMatchIndex<iCloseIndex){
            str = str.replaceBetween(iMatchIndex, iMatchIndex+4, ">");
            iStartPosition = iCloseIndex;
        }else{
            break;
        }    
    }
    return str;
}

replaceGreaterThen(str6);