Vlad Ivanov Vlad Ivanov - 24 days ago 6
HTML Question

How to replace spaces in label tag with <br>?

How can I replace all spaces in <label> tag with <br>?
For example I have:

<label>Some text here</label>


And change it to:

<label>Some<br>text<br>here</label>


I try to use this code:

$('.form-group label').html().replace(' ', '<br>');


But it didn't working.

Answer

Use html() method with a callback function. And for replacing all the space use regex with global falg in String#replace method.

$('label').html(function(i, oldHTML) {
  return oldHTML.replace(/\s+/g, '<br>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Some text here</label>

Comments