There are three issues with your code:
$('.WorkingHours').text()
won't contain any HTML (so no br
tags either), it only returns the text content of elements.
$('.WorkingHours').text()
returns:
M,W,Th,F 7:30 AM - 4:00 PMTu 7:30 AM - 6:00 PM
whereas $('.WorkingHours').html()
returns:
M,W,Th,F 7:30 AM - 4:00 PM<br>Tu 7:30 AM - 6:00 PM<br>
You have to escape the inner backslash in your expression. Edit: Having a look at the output of .html()
it actually does not contain <br />
but <br>
. This might depend on the doctype of the document (not working example, working example).
You have to assign the value back to the element.
You might be able to do
$('.WorkingHours').html(function(i, html) {
return html.replace(/<br\s*\/?>/g, " ");
});
but it would be much cleaner to not use regular expressions at all:
$('.WorkingHours').find('br').replaceWith(' ');
This finds all br
element nodes and replaces them with a text node containing only a space.
DEMO
Update (in response to one of your comments): If you want to replace the last br
with a full stop, you can use .last()
:
$('.WorkingHours')
.find('br').last().replaceWith('.')
.end().replaceWith(' ');
DEMO