Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery how to insert <br/> tag after every Semicolon

I am dumping some CSS into a div and I am looking to format it so it is more legible. Basically what I want to do is insert a break tag after every semicolon. I have searched around for a while but can't seem to find something that quite fits what I am trying to do.

I have something like this...

HTML

<div class='test'>
color:red;background-color:black;
</div>​

jQuery

var test = $('.test').text();
var result = test.match(/;/g);   

alert(result);​

And I have tried..

var test = $('.test').text();
var result = test.match(/;/g);   

result.each(function(){
$('<br/>').insertAfter(';');
});    

alert(result);​

Also I have started a fiddle here.. Which basically just returns the matched character... http://jsfiddle.net/krishollenbeck/zW3mj/9/ That is the only part I have been able to get to work so far.

I feel like I am sort of heading down the right path with this but I know it isn't right because it errors out. I am thinking there is a way to insert a break tag after each matched element, but I am not really sure how to get there. Any help is much appreciated. Thanks...

like image 651
Kris Hollenbeck Avatar asked Sep 05 '12 16:09

Kris Hollenbeck


2 Answers

try it like this

var test = $('.test').text();
var result = test.replace(/\;/g,';<br/>');   

$('.test').html(result);​

http://jsfiddle.net/Sg5BB/

like image 171
wirey00 Avatar answered Oct 11 '22 15:10

wirey00


You can use a normal javascript .replace() method this way:

​$(document)​.ready(function(){
    $(".test").html($(".test").html().replace(/;/g, ";<br />"));
});​

Fiddle: http://jsfiddle.net/SPBTp/4/

like image 26
Praveen Kumar Purushothaman Avatar answered Oct 11 '22 14:10

Praveen Kumar Purushothaman