Replace each value of a string with data from an array js

2

Replace each value of a string with data from an array with js or jquery

var numbers = ["0:00", "0:01", "0:05"];
for (var i = numbers.length - 1; i >= 0; i--) {

   str = "0:00 oki 0:01".split(numbers[i]).join("");
    //console.log(str);
}
console.log(str);

I got back oki 0:01 And I need you to come back just oki

    
asked by ztvmark 27.08.2016 в 05:23
source

3 answers

1

The problem is that each loop returns to process the entire chain, what you must do is define the chain outside the loop. I added .trim () at the end to remove the blanks.

var numbers = ["0:00", "0:01", "0:05"];
var str="0:00 oki 0:01";
for (var i = numbers.length - 1; i >= 0; i--) {

   str = str.split(numbers[i]).join("").trim();
    //console.log(str);
}
console.log(str);
    
answered by 27.08.2016 в 07:53
1

If I did not understand wrong you need to filter the elements that match the first array and only those elements of the string that do not have similarity and remove the blank spaces, well I would not use a for cycle for that , better I would take the method of the array object, Array.prototype.filter to have said result, your code would look like this:

var numbers = ["0:00", "0:01", "0:05"];
var str="0:00 oki 0:01";
str = str.split(' ').filter(function(value){ 
   return numbers.indexOf(value) == -1 // Si el valor no existe devolvera true por lo tanto sabremos que valores no estan en el primer array y los filtrara, esto devuelve ["oki"]
} ).join('');
console.log(str) // salida --> oki
    
answered by 27.08.2016 в 12:08
0

I think the best solution would be to use a regular expression :

var numbers = ["0:00", "0:01", "0:05"];
var reg = new RegExp(numbers.join('|'), 'g');
var nuevoStr = 
    '0:00 oki 0:01'
              .replace(reg, '') // Cambia los valores capturados con el RegExp
              .trim();          // Elimina los espacios en blanco
console.log(nuevoStr);
    
answered by 27.08.2016 в 15:04