简体   繁体   English

如何将 JS 多行字符串转换为带制表符的单行

[英]How to convert JS multi-line string to single-line with tabs

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.自动将其转换为单行字符串,使用 \n 表示中断,使用 \t 表示制表符。

After conversion it should look like:转换后它应该如下所示:

const code = " \n\tThis is some code\n " const code = " \n\tThis is some code\n "

How can this be done in JavaScript?如何在 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:一种解决方案可能是找到 4 个空格并将其替换为\t ,如下所示:

 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.由于 OP 说结果应该是\n\tThis is some code\n ,我也用空字符串替换了<code></code>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM