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

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

I want to format this date:


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 tag, as follows:



What I did:


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


Solution 1:

Using split()

Snippet :

var data =$('#date').text();
var arr = data.split('/');
$("#date").html("<span>"+arr[0] + "</span></br>" + arr[1]+"/"+arr[2]);	  
<script src=""></script>
<div id="date">23/05/2013</div>


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

Solution 2:

Instead of using substring with a fixed index, you’d better use replace :

    return t.replace(/^([^\/]*\/)/, '<span>$1</span><br>')

One advantage is that it would still work if the first / is at a different position.

Another advantage of this construct is that it would be extensible to more than one elements, for example to all those implementing a class, just by changing the selector.

Demonstration (note that I had to select jQuery in the menu in the left part of jsfiddle’s window)

Solution 3:

You should use html():


    $("#date").html('<span>'+$("#date").text().substring(0, 2) + '</span><br />'+$("#date").text().substring(3));     

Solution 4:


date.innerHTML= date.innerHTML.replace(/^(..)\//,'<span>$1</span></br>')
<div id="date">23/05/2013</div>

Solution 5:

use this

<div id="date">23/05/2013</div>
<script type="text/javascript">
  var x = $("#date").text();
    x.text(x.substring(0, 2) + '<br />'+x.substring(3));     

Solution 6:

Try this



Look a regular expression

enjoy us 😉

Related:  How do I escape quotes in HTML attribute values?