Replace multiple word Ivs

Asked

Viewed 104 times

-1

Supposing I did have:

<div class='datas'>
 <span>01-01-2019</span>
 <span>01-02-2019</span>
</div>

<div class='datas'>
 <span>01-03-2019</span>
 <span>01-03-2019</span>
</div>

How can I exchange all strokes for slashes so that it is in the format day/month/year?

  • A good practice would be to render the already formatted date, for all possible scenarios this would be the best.

2 answers

3


Ericki,

There are several ways to do this, below two examples, using only JS and another with Jquery:

//Com JS puro
function transformaData() {
  //Pego as divs com a class datas
  let divs = document.getElementsByClassName("datas");

  for (let i = 0; i < divs.length; i++) {
    //Para cada div, procura as tags span
    let spans = divs[i].getElementsByTagName("span");

    for (let j = 0; j < spans.length; j++) {
      //Altera o valor presente, substituindo o (-) por (/)
      spans[j].innerHTML = spans[j].innerHTML.replace(/-/g, "/");
    }
  }
}

//JQuery
$(function(){
    //Adiciona via JQuery o click no botão
    $("#btn-jquery").click( function() {
      //Procura a tag span dentro da class datas
      $(".datas span").each( function() {
        //O each vai entrar nessa função para cada elemento encontrado
        let value = $(this).text();
        //Pego o valor anterior, altero e já faço a atualização do mesmo no elemento
        $(this).text( value.replace(/-/g, "/") );
      });
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class='datas'>
  <span>01-01-2019</span>
  <span>01-02-2019</span>
</div>

<div class='datas'>
  <span>01-03-2019</span>
  <span>01-04-2019</span>
</div>

<button onclick="transformaData()">Alterar data apenas com JS</button>
<button id="btn-jquery">Alterar data com JQuery</button>

1

Solution:

  1. Foreach each element with method each.
  2. Save in a Let the values that was returned from the method replace
  3. Put the value in the HTML with the method text.

function substituir_palavara_de_varias_divs() {
  $(".datas span").each(function(index) {
    let replace = $(this).text().replace(/-/g, "/");
    $(this).text(replace);
  });
}
substituir_palavara_de_varias_divs()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='datas'>
  <span>01-01-2019</span>
  <span>01-02-2019</span>
</div>

<div class='datas'>
  <span>01-03-2019</span>
  <span>01-04-2019</span>
</div>

Source:

.text()

.each()

String.prototype.replace

Browser other questions tagged

You are not signed in. Login or sign up in order to post.