Show array with hyphen instead of comma

0

I am showing an array from javascript using the following for :

for (var y = 0; y < arrayHay.length; y++) {
     $(".reporteBody").append('<div class="cajaResult"><h3>Caja #' + arrayHay[y] + "</h3><p>" + arrayMaximo[y] + "</p></div>");
}

Which shows it to me like this:

How can I show the same array only with a hyphen instead of the comma?

Thank you very much for the help.

EDITED

I'm dealing with the following form and I still do not care about the commas:

for (var y = 0; y < arrayHay.length; y++) {
     str = arrayMaximo[y].toString();
     str.replace(",", "-");
     console.log("Cadena nueva:", str);
     $(".reporteBody").append('<div class="cajaResult"><h3>Caja #' + arrayHay[y] + "</h3><p>" + str + "</p></div>");
}
    
asked by Baker1562 24.02.2018 в 20:20
source

2 answers

2

Reasons why it does not work for you and its solutions:

  • replace changes the string specified by the new string ... but does not change the original string . That is why it is not enough to make str.replace(",", "-") you must assign the value again: str = str.replace(",", "-") .

  • Even if you correct what is indicated in step 1, it will still not work because as that replacement is specified, it will only affect the first occurrence. You should use regular expressions to indicate that you want all occurrences replaced. You can do that by doing str = str.replace(/,/g, "-") .

  • With those changes the code already works:

    arrayHay = [1,5];
    arrayMaximo = [ [1,5,21,9], [16] ]
    
    for (var y = 0; y < arrayHay.length; y++) {
         str = arrayMaximo[y].toString();
         str = str.replace(/,/g, "-");
         console.log("Cadena nueva:", str);
         $(".reporteBody").append('<div class="cajaResult"><h3>Caja #' + arrayHay[y] + "</h3><p>" + str + "</p></div>");
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="reporteBody"></div>

    As another option, instead of using replace you could have done join and saved yourself the intermediate step of character replacement:

    arrayHay = [1,5];
    arrayMaximo = [ [1,5,21,9], [16] ]
    
    for (var y = 0; y < arrayHay.length; y++) {
         str = arrayMaximo[y].join("-");
         console.log("Cadena nueva:", str);
         $(".reporteBody").append('<div class="cajaResult"><h3>Caja #' + arrayHay[y] + "</h3><p>" + str + "</p></div>");
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="reporteBody"></div>
        
    answered by 24.02.2018 / 23:03
    source
    2

    With the replace function:

    str = arrayHay[y];
    str.replace(",", "-", "gi");
    

    Source

    This example checks that it works.

    arrayHay = ["1,5,21,9"];
    str = arrayHay[0];
    alert(str);
    var re = /,/gi;
    str2 = str.replace(re, "-");
    alert( str2 );
    

        
    answered by 24.02.2018 в 21:01