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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.