-1

How can I transform a string to display newlines (\n) and tabs using javascript?

Example Input

// Get position of the element clicked
var getPosition = function(element) {
    var xP = (element.offsetLeft + element.clientLeft);
    var yP = (element.offsetTop + element.clientTop);
    return {x: xP, y: yP};
};


Expected Output

// Get position of the element clicked\nvar getPosition = function(element) {\n    var xP = (element.offsetLeft + element.clientLeft);\n    var yP = (element.offsetTop + element.clientTop);\n    return {x: xP, y: yP};\n};\n\n
Cezar Cobuz
  • 1,077
  • 1
  • 12
  • 34
  • Possible duplicate of [Javascript - How to show escape characters in a string?](https://stackoverflow.com/questions/21672334/javascript-how-to-show-escape-characters-in-a-string) – V. Sambor Sep 23 '19 at 09:29

1 Answers1

3

Just use JSON.stringify(str) like so:

const input = `// Get position of the element clicked
var getPosition = function(element) {
    var xP = (element.offsetLeft + element.clientLeft);
    var yP = (element.offsetTop + element.clientTop);
    return {x: xP, y: yP};
};

`;

console.log(JSON.stringify(input));
MauriceNino
  • 6,214
  • 1
  • 23
  • 60