Search code examples
javascriptjquerydatesplitsubstring

How to split a string at the first `/` (slash) and surround part of it in a `<span>`?


I want to format this date: <div id="date">23/05/2013</div>.

First I want to split the string at the first / and have the rest in the next line. Next, I’d like to surround the first part in a <span> tag, as follows:

<div id="date">
<span>23</span>
05/2013</div>
23
05/2013

What I did:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="date">23/05/2013</div>
<script type="text/javascript">
  $(document).ready(function() {
    $("#date").text().substring(0, 2) + '<br />';
  });
</script>

See the JSFiddle.

But this does not work. Can someone help me with jQuery?


Solution

  • Using split()

    Snippet :

    var data =$('#date').text();
    var arr = data.split('/');
    $("#date").html("<span>"+arr[0] + "</span></br>" + arr[1]+"/"+arr[2]);	  
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="date">23/05/2013</div>

    Fiddle

    When you split this string ---> 23/05/2013 on /

    var myString = "23/05/2013";
    var arr = myString.split('/');
    

    you'll get an array of size 3

    arr[0] --> 23
    arr[1] --> 05
    arr[2] --> 2013