0

I have an application in which user can do some actions with ajax calls. When ajax call is done then the results of the action is append into my div with id = "log". I want to make a user option (button - Export) when he is done with his work that he can export his "activity log" into .txt file. So far i have succeed doing that but html converts into txt file with tags etc. I would like to remove tags and format a bit that .txt file but don't know how.

My HTML code is

<input type="button" value="Export" onclick="exportLog();">
<div id="log">
    <p>Action 1 successful</p>
    <p>Action 2 unsuccessful </p>
    <p>Action 4 - contact admin</p>
    <p>...etc</p>
</div> 

Javascript code is

function exportLog(){
    var elHtml = document.getElementById('log').innerHTML;
    var link = document.createElement('a');
    var mimeType = 'text/plain';

    link.setAttribute('download', 'logFile');
    link.setAttribute('href', 'data:' + mimeType  +  ';charset=utf-8,' + encodeURIComponent(elHtml));
    link.click();
}

I did this with a help of this. It works but my .txt file is like

<p>Action 1 successful</p><p>Action 2 unsuccessful </p><p>Action 4 - contact admin</p><p>...etc</p>

and i would like to look like

Action 1 successful
Action 2 unsuccessful 
Action 4 - contact admin
...etc

How to achieve this?

Community
  • 1
  • 1
KuKeC
  • 4,392
  • 5
  • 31
  • 60

2 Answers2

2

First Method: change innerHTML to innerText

Your working code

I changed only this line

var elHtml = document.getElementById('log').innerText;

Second method:

you can use textContent API

JsFiddler link

PS : I am able to get the text with newline characters with both the methods

Please refer the screenshot of my text editor for your reference.

enter image description here

NiRUS
  • 3,901
  • 2
  • 24
  • 50
  • It removes the tags but still all values goes in 1 line, but as you can see on my question that i would like new line to each

    tag.

    – KuKeC Jan 14 '16 at 09:22
  • Yes you are right, but why my notepad (windows 10) doesn't show me each line in own row and other programs do show it? Now I am confused a lot. – KuKeC Jan 14 '16 at 09:31
  • @KuKeC i have updated the answer with possible options. I can see the newline being applied in the formatting of the text and text editors recognise it correctly. – NiRUS Jan 14 '16 at 09:35
  • Thanks on fast and simple solution. +1 :) – KuKeC Jan 14 '16 at 09:36
1

Ok, if to use only p tag, then this should work

var stringWithNewLines = logContent.replace(/<p>(.+?)<\/p>/g, function(str, p1, offset, s) {
      return p1 + "\n"; 
});
Sergii Shvager
  • 1,226
  • 9
  • 14