khollenbeck
khollenbeck

Reputation: 16157

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...

Upvotes: 5

Views: 9229

Answers (5)

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167182

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/

Upvotes: 3

Guffa
Guffa

Reputation: 700362

You can't use jQuery selectors on text, it only works on elements.

Get the text, just replace each ; with ;<br/>, and put it back.

$('.test').html($('.test').text().replace(/;/g, ';<br/>'));

Upvotes: 1

samisadaka
samisadaka

Reputation: 91

Try something like this :

var test = $('.test').text(); var result = test.replace(/;/g,";
");
$('.test').html(result); ​ That should work if you stick it into your jfiddle.

Upvotes: 0

Ashirvad
Ashirvad

Reputation: 2377

Use This CODE

var test = $('.test').text();
var result = test.split(';').join(';<br />')   

http://jsfiddle.net/FmBpF/

Upvotes: 2

wirey00
wirey00

Reputation: 33661

try it like this

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

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

http://jsfiddle.net/Sg5BB/

Upvotes: 12

Related Questions