Home > Mobile >  Replace specific character from an Array of objects with another character in JS
Replace specific character from an Array of objects with another character in JS

Time:03-05

I'm trying to replace character "/" with a blank space or a dash "-", but i can't seem to figure out how. I've tried some of the answers i've found here but it returns the same string. I have two set of arrays.

set A: elemnts = ["String1", "String2", "String3/"] set B gets each character of a s string from A to evaluate, an replace in case "/" is found.

 for(var i=0; i< elements.length; i  ){
          arrayV = elements[i].value;
             for (var j=0; j <= arrayV.length; j  ) {

                if(arrayV.charAt(j) === '/'){
arrayV[j] = "-";
                 }
   
    
                }
    
                elements[i]= arrayV;
       }

This is how i solved it (i learned something today):

var elements = document.getElementsByName("inputCont");

for(var i=0; i< elements.length; i  ){

      var rString = elements[i].value;
  
         rString = rString.replace('/','-');
        
         elements[i].value = rString;
   }

CodePudding user response:

In this example I use the function map() to create a new array and replace() to replace the character.

var elemnts = ["String1", "String2", "String3/"];

var result = elemnts.map(str => str.replace('/','-'));

console.log(result);

  • Related