0

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);
3
  • 2
    but am missing a piece of the puzzle -> at least the error message in the console Commented Aug 14, 2015 at 21:22
  • 1
    split() is a string function and data is an array. Do you want to return a new array with replaced values or should you be turning the array into a string first? Commented Aug 14, 2015 at 21:23
  • I'd like to return the array with the new values. Commented Aug 14, 2015 at 21:23

2 Answers 2

3

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);
    })
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I updated my fiddle and see that gets me much closer but the array isn't swapping out my values. jsfiddle.net/dntreply/pc8y5un5/7
0
      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, ''));

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.