You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Monaco Editor显示\n与\"转义字符?

解决方案

要让Monaco Editor原样显示\n和\"这类转义字符,核心是对字符串进行双重转义——因为JavaScript会自动解析第一层转义字符,只有把转义符本身也转义,才能让它们以原始形式呈现在编辑器中。

修改后的代码如下:

editor_source = monaco.editor.create(document.getElementById('editor_source'), {
    value: "{\\n  \\\"message\\\": \\\"¡Hello World!\\\", \\n  \\\"status\\\": \\\"successful\\\"\\n}",
    language: 'plaintext',
    wordWrap: 'on',
    tabSize: 2,
    indentSize: 2,
})

原理说明

  • 原本的\n会被JavaScript解析为换行符,改成\\n后,会被解析为字符串\n,从而在编辑器中显示原始转义字符;
  • 原本的\"会被解析为双引号",改成\\\"后,会被解析为字符串\",实现原样显示;
  • 保持language: 'plaintext'即可,无需切换其他语言模式。

修改后,编辑器将输出你期望的内容:

{\n  \"message\": \"¡Hello World!\", \n  \"status\": \"successful\"\n}

内容的提问来源于stack exchange,提问作者Edinson Mauricio Mendoza E.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 01:27:37