3

I have the following code snippet to convert html to javascript, but I seem to be facing an issue with the output when bound to a textarea and I am not able to figure out what the issue could be.

var html_to_text = $('#source').val().replace('&nbsp;', ' ').replace(/<[^>]*>/g, '').replace(/(<br>)+/g, '<br>');

The output is correct when displaying on an alert, but, when the same is bound to a text area, there is a lot of white space on it. Could someone help me understand what could be the issue with the above snippet.

I have a working sample of the same at http://jsfiddle.net/technicaliti/uuxDx/

Abishek
  • 11,191
  • 19
  • 72
  • 111
  • 1
    What's the problem? You have a lot of whitespace (`\n` and spaces) in your original HTML, and you're removing a lot of non-whitespace. Which leaves...a lot of whitespace. Also, your first `.replace()` call doesn't use a Regular Expression, so it's only going to replace the first occurrence of a (nonexistent) ` ` – Ian Aug 06 '13 at 04:40
  • How does it show the correct output on the alert and not on the #destination textarea. Am i missing something? – Abishek Aug 06 '13 at 04:41
  • I see a lot of whitespace in both the alert and the textarea. – Ian Aug 06 '13 at 04:43
  • Do you need to add .replace(/\s{2,}/g, '\n\r') to the chain? – SaganRitual Aug 06 '13 at 04:46
  • 1
    `$('#source').val().replace(/<[^>]*>/g, '').replace(/\n/g, '');` –  Aug 06 '13 at 04:57
  • @rps, that still keeps the   as is. @Ian, I have change the nbsp; replace to `.replace(/[&]nbsp[;]/gi," ")`. Hope this is good – Abishek Aug 06 '13 at 05:03

3 Answers3

0

Add .replace(/\s{2,}/g, '\n\r') to the end.

SaganRitual
  • 3,143
  • 2
  • 24
  • 40
  • 2
    1>the correct order is `\r\n` **not** `\n\r` 2>that would replace whitespace,\r,\f to newline – Anirudha Aug 06 '13 at 04:49
  • This answer works correctly without loosing the format and with the improvement suggested by @Anirudh. – Abishek Aug 06 '13 at 04:51
0

.replace(/\r?\n|\r/g,"");

This one removes only multiple newlines (taken from this answer) so you still get a nice format

Demo fiddle

Community
  • 1
  • 1
omma2289
  • 54,161
  • 8
  • 64
  • 68
0

Just replace the line break with nothing.

        html_to_text = html_to_text.replace(/\n/g, ''); 
shakthydoss
  • 2,551
  • 6
  • 27
  • 36