Manipulate fix element characters in JavaScript [duplicated]

1

I have started to learn to use JavaScript, I have no experience in this kind of languages. Basically what I want to do is replace some characters of the names of the elements, for example, the following program gives me the 4 fruits, at the time of printing I would like to replace the "a" por "4" and the "g" por "j" .

Is this possible in JavaScript?

var fruits, text, fLen, i;

fruits = ["Banana", "Orange", "Apple", "Mango"];
fLen = fruits.length;
text = "<ul>";
for (i = 0; i < fLen; i++) {
    text += "<li>" + fruits[i] + "</li>";
}
text += "</ul>";
document.getElementById("demo").innerHTML = text;
<p>The best way to loop through an array is using a standard for loop:</p>
<p id="demo"></p>
    
asked by Saul 02.05.2017 в 00:41
source

2 answers

0

You can use the split() methods in conjunction with join() or as indicated by @Dev. Joel , with: replace() but the latter will do it only with the first occurrence unless you use regular expressions , attach an example that shows the 3 ways (among others) to do it:

var fruits, text, fLen, i;

fruits = ["Banana", "Orange", "Apple", "Mango"];
fLen = fruits.length;
text = "<ul>";
for (i = 0; i < fLen; i++) {

    // con split() + join()
    text += "<li>" + fruits[i].split("a").join("4").split("g").join("j") + "</li>";

    // con replace() ...solo la primera ocurrencia.
    text += "<li>" + fruits[i].replace("a","4").replace("g","j") + "</li>";

    // con replace() + expresiones regulares
    text += "<li>" + fruits[i].replace(/[ag]/g,function(e) {
     return ( e=="a" ) ? "4" : "j";
    }) + "</li>";
}
text += "</ul>";
document.getElementById("demo").innerHTML = text;
<p>The best way to loop through an array is using a standard for loop:</p>
<p id="demo"></p>
    
answered by 02.05.2017 / 01:36
source
0

This can work, what it does is pass the elements ( string ) for a Array.prototype.map() and replace the characters that the regexp identifies.

var fruits, fruitsIn, text, fLen, i;

fruitsIn = ["Banana", "Orange", "Apple", "Mango"];

fruits = fruitsIn.map(function (fruit) {
  return fruit.replace(/[ag]/g, function (character) {
    switch (character) {
      case 'a': return '4'
      case 'g': return 'j'
    }
  })
})

fLen = fruits.length;

text = "<ul>";
for (i = 0; i < fLen; i++) {
    text += "<li>" + fruits[i] + "</li>";
}
text += "</ul>";
document.getElementById("demo").innerHTML = text;
<p>The best way to loop through an array is using a standard for loop:</p>
<p id="demo"></p>
    
answered by 02.05.2017 в 02:19