Skip to content
Advertisement

Replace multiple &nbsp with multiple whitespace

I retrieve an HTML string from the database and needed to change all  s’ to white spaces

JavaScript

so I wanted the change the   to whitespaces, so i can use in a pre element

JavaScript

as following

JavaScript

I need a solution to do this either in PHP, JS / Jquery

Please Help me through out this

I have tried

JavaScript

I tried This but this replaces all nbsp’s to one white space

Advertisement

Answer

Even inside <pre> tags, HTML tags will be turned into DOM elements and the browsers will collapse multiple spaces into one. Here is an example of this behavior.

JavaScript

Also, in order to replace multiple occurrences of the search string, you’ll have to use a regular expression in the first parameter of .replace().

Solution

This uses a rudimentary way to replace HTML tags in the string, but that’s outside the scope for this question. I added it to be able to reproduce your case and be able to provide a solution.

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement