ndesign11
ndesign11

Reputation: 1779

Replace string in JS array without using native replace() method

I am stuck a bit with replacing string in js array. I am trying to log the arguments to see what is going on but am missing a piece of the puzzle.

fiddle

// - trying to look for substring in array 
// - if match is found 
// - replace substring without using the native method replace();

var div = $('.insert');

data = ["erf,", "erfeer,rf", "erfer"];
data = data.map(function (x) {
    return /""/g.test(x) ? x.replace(/""/g, "") : x
});

function fakeReplace(data, substr, newstr) {

//should show   ["erf,", "erfeer,rf", "erfer"];      
div.append("data before match replace = " + data);

    div.append("\<br>");
    div.append("substr = " + substr);
    div.append("\<br>");
    div.append("newstr = " + newstr);
    div.append("\<br>");

    return data.split(substr).join(newstr);
}

fakeReplace(data, "erf", "blue");

//should show ["blue,", "blueeer,rf", "blueer"];
div.append("data after fakeReplace is executed = " + data);

Upvotes: 0

Views: 2525

Answers (2)

Javidan
Javidan

Reputation: 1

      let myString = "Victor";
      let splitted = myString.split('');

      function replaceManual(a,b){

      for(let i = 0; i<= splitted.length-1; i++)
       {

          for(let j=i; j <=i;j++)
           {
             if(splitted[j]===a)
              {
                splitted[j]=b;
                return splitted;
              }
                else
              {
                break;
             }   
            }
          }
          }
   replaceManual('V','T');

   console.log(splitted.toString().replace(/[^\w\s]/gi, ''));

Upvotes: 0

Malk
Malk

Reputation: 11983

You are treating data like a string in your function. You can use map() to return a new array with each element replaced.

function fakeReplace(data, substr, newstr) {
    return data.map(function(s) {
       return s.split(substr).join(newstr);
    })
}

Upvotes: 3

Related Questions