Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How do I split a string into multiple parts?

Answer: You just have to pass (“”) in the regEx section of the Java Split() method. This will split the entire String into individual characters.

How do you split a string at a certain character?

To split a string with specific character as delimiter in Java, call split() method on the string object, and pass the specific character as argument to the split() method. The method returns a String Array with the splits as elements in the array.

How do I split a word in a string?

The split() method splits a string into a list. You can specify the separator, default separator is any whitespace.


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

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)


You should use html():

SEE DEMO

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

try

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