-3

I want to do str_replace in javascript but without using an inbuilt function. I want Scratch Code for this.

Please Someone can have the code for this? I WANT JAVASCRIPT INBUILt FUNCTION STR_REPLACE DITTO without USING STR_REPLACE.

function Replace(string, charToChange, charToReplace){
var replaced = "";
for(var i=0; i < string.length; i++){
    if(string[i] == charToChange){
        replaced = charToReplace;
    } 
}
return replaced;
}
Rushabh Shah
  • 5
  • 1
  • 6

4 Answers4

0

JS has a function for replace. go through this link: https://www.w3schools.com/jsref/jsref_replace.asp

Sahal Tariq
  • 198
  • 1
  • 9
0

Try the below example

enter code here

    function myFunction() 
           {
              var str1 = 'This is a test string.';
            // Let's replace the word This with 'that'
             str1 = str1.split('This').join('that');   
        }

Note : The string inside the split function is case sensitive. Hope this will help you...

0

You can try below code

var string = "abc Code Snippet abc pqr abc";
var result = string.split(' ');
var i =0;
result.forEach(function(element){
if(result[i] == "abc"){
result[i] = "change";
}
i++;
});
var a = result.join(" "); 
alert(a);
0

Please note the following is entirely under the assumption that you can't use built in functions which is stated by OP in comments

function Replace(s, strOld, strNew){
    //find returns the starting index of the string you are looking for
    // do some exception handling or return -1 if not there
    var loc = find(s, strOld); //you should implement find
    //assuming you can't use the slice function
    retStr = "";
    for(var i = 0; i < loc; i++){
        retStr += s[i]; //builds new string with chars up to loc
    }
    retStr += strNew; //put the new string in
    for(var i = loc + strOld.length; i < s.length; i++){
        retStr += s[i]; //puts remaining chars from original string
    }
    return retStr;

}

Do something like this. I left the find function up to you but the rest is a pretty simple algorithm. Find should check s by character for matches with strOld that happen in a row.

Note: I changed the variable names from your original function. string to s because it's bad form to name a variable after a type. I changed the other two because they are misleading, since you are trying to replace a string not a char.

I'd also recommend you use === instead of == for equality until you understand what the difference is. See here for more

Community
  • 1
  • 1
Matthew Ciaramitaro
  • 1,184
  • 1
  • 13
  • 27