admin管理员组

文章数量:1405564

I want to include this kind of code to a second place.

<div id="social-links">
  <!-- Facebook -->
  <a href="" target="_blank">
    <i class="fa fa-facebook-square fa-lg"></i>
    Facebook
  </a>
  &nbsp;

  <!-- Google+ -->
  <a href="/+name" target="_blank">
    <i class="fa fa-google-plus fa-lg"></i>
    Google+
  </a>
  &nbsp;
</div>

Because of the available width I want to replace the &nbsp; with <br/>.

This is my current code but it doesn't work:

$( "&nbsp;" ).replaceWith( "<br/>" );

JSFiddle

I want to include this kind of code to a second place.

<div id="social-links">
  <!-- Facebook -->
  <a href="https://www.facebook./name" target="_blank">
    <i class="fa fa-facebook-square fa-lg"></i>
    Facebook
  </a>
  &nbsp;

  <!-- Google+ -->
  <a href="https://plus.google./+name" target="_blank">
    <i class="fa fa-google-plus fa-lg"></i>
    Google+
  </a>
  &nbsp;
</div>

Because of the available width I want to replace the &nbsp; with <br/>.

This is my current code but it doesn't work:

$( "&nbsp;" ).replaceWith( "<br/>" );

JSFiddle

Share Improve this question edited Aug 9, 2014 at 19:04 Peleke asked Aug 9, 2014 at 19:02 PelekePeleke 9613 gold badges11 silver badges26 bronze badges 2
  • 3 Why not using a decent text editor? – Thomas Junk Commented Aug 9, 2014 at 19:06
  • How do you know which one hes using? – Lucas T. Commented Aug 9, 2014 at 19:10
Add a ment  | 

4 Answers 4

Reset to default 6

here you go:

$('#social-links').html($('#social-links').html().replace(/&nbsp;/g,"<br/>"));

UPDATE:

Now that I think about it again after 3 years, I'd do it this way:

const $socialLinks = $('#social-links');
$socialLinks.html($socialLinks.html().split('&nbsp;').join('<br/>'));

It has much better performance than the previous code.

If you like plain JS:

var socialLink = document.getElementbyId("social-links");
socialLink.innerHTML = socialLink.innerHTML.replace(/&nbsp;/g,"<br/>");

You can use:

$('#social-links').html($('#social-links').html().replace(/&nbsp;/g, '<br/>'))

Ah man, late to the party!

Fixed here in a slightly longer version:

$("div").each(function() {
    var $this = $(this);
    $this.html($this.html().replace(/&nbsp;/g, '<br/>'));
});

http://jsfiddle/kitsonbroadhurst/jyrv8e3j/2/

This question has been asked before by the way: Is it possible to remove '&nbsp' using JQuery..?

Try a thorough search before asking next time

本文标签: javascriptReplace nbsp with ltbrgtStack Overflow