I want to take a string, such as
const code = `
<code>
This is some code
</code>
`
and convert it automatically to a one line string, using \n for breaks and \t for tabs.
After conversion it should look like:
const code = "\n\tThis is some code\n
"
How can this be done in JavaScript? I saw posts solving how to add line breaks, but found nothing for tab support.
CodePudding user response:
one solution could be to find 4 spaces and replace it by \t
like this:
const code = `
<code>
This is some code
</code>
`;
const result = code.replace(/ {4}/g, '\\t').replace(/<\/*code>\n?/g, '').replace(/\n/g, '\\n');
console.log(result);
since OP has said result should be \n\tThis is some code\n
, I've also replaced <code></code>
with empty string.