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/

6
  • 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) &nbsp; Commented Aug 6, 2013 at 4:40
  • How does it show the correct output on the alert and not on the #destination textarea. Am i missing something? Commented Aug 6, 2013 at 4:41
  • I see a lot of whitespace in both the alert and the textarea. Commented Aug 6, 2013 at 4:43
  • Do you need to add .replace(/\s{2,}/g, '\n\r') to the chain? Commented Aug 6, 2013 at 4:46
  • 1
    $('#source').val().replace(/<[^>]*>/g, '').replace(/\n/g, ''); Commented Aug 6, 2013 at 4:57

3 Answers 3

0

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

2
  • 2
    1>the correct order is \r\n not \n\r 2>that would replace whitespace,\r,\f to newline Commented Aug 6, 2013 at 4:49
  • This answer works correctly without loosing the format and with the improvement suggested by @Anirudh. Commented Aug 6, 2013 at 4: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

0

Just replace the line break with nothing.

        html_to_text = html_to_text.replace(/\n/g, ''); 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.