How to split a string at the first `/` (slash) and surround part of it in a `<span>`?
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] --> 23arr[1] --> 05arr[2] --> 2013
Instead of using substring with a fixed index, you'd better use replace
:
$("#date").html(function(t){ 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)