什么是字符串转义?
字符串转义是在字符串字面量中具有特殊含义的字符前插入反斜杠(或其他标记)的过程。当编程语言解析器在双引号字符串内遇到双引号时,会将其视为字符串的结尾。使用反斜杠对引号进行转义——写成 \" 而非 "——告诉解析器将其视为普通字符而非分隔符。所有使用字符串字面量的语言都有转义规则,尽管具体的转义序列有所不同。
最常见的转义序列对应于无法直接出现在源代码中的空白字符和控制字符。换行符变为 \n,制表符变为 \t,字面反斜杠变为 \\。这些约定可追溯至 C 编程语言(ISO/IEC 9899),并已被 JavaScript(ECMA-262)、Python、Java、Go 和 Rust 采用。JSON(RFC 8259)使用相同的语法,但支持的转义序列集合较小。
反转义(有时也称为"去转义")是逆向操作:将转义序列还原为原始字符。这在读取日志文件、解析 API 响应或调试经过双重转义的数据时很常见。两种操作手动执行既繁琐又容易出错,因此开发者在处理多行字符串、内嵌引号或 Unicode 字符时往往借助转义/反转义工具。
为什么要使用在线字符串转义工具?
手动添加或删除反斜杠既繁琐又容易出错,尤其是面对嵌套引号或多行输入时。基于浏览器的字符串转义工具可即时返回结果,无需搭建 REPL 或编写临时脚本。
字符串转义使用场景
转义序列参考表
下表列出了常见的转义序列,以及它们在 JavaScript、Python 和 JSON 中是否受支持。三种语言共享核心集合(换行符、制表符、反斜杠、双引号),但在单引号、十六进制转义和扩展 Unicode 表示方式上存在差异。
| 序列 | 含义 | JavaScript | Python | JSON |
|---|---|---|---|---|
| \n | Newline (LF) | Yes | Yes | Yes |
| \r | Carriage return | Yes | Yes | Yes |
| \t | Tab | Yes | Yes | Yes |
| \\ | Backslash | Yes | Yes | Yes |
| \" | Double quote | Yes | Yes | Yes |
| \' | Single quote | Yes | Yes | No |
| \b | Backspace | Yes | Yes | Yes |
| \f | Form feed | Yes | Yes | Yes |
| \v | Vertical tab | Yes | Yes | No |
| \0 | Null character | Yes | Yes | No |
| \xNN | Hex byte | Yes | Yes | No |
| \uNNNN | Unicode (BMP) | Yes | Yes | Yes |
| \u{N..} | Unicode (full) | Yes | No | No |
JavaScript vs Python vs JSON 转义对比
虽然这三种格式共享相同的反斜杠语法,但在有效序列和边界情况处理上存在差异。选错模式会产生看似正确但在解析时失败的输出。
代码示例
以下是在 JavaScript、Python、Go 和命令行中进行字符串转义和反转义的示例。
// Escape a string with special characters
const raw = 'Line 1\nLine 2\tTabbed "quoted"';
const escaped = JSON.stringify(raw);
// → '"Line 1\\nLine 2\\tTabbed \\"quoted\\""'
// Unescape a JSON string value
const input = '"Hello\\nWorld"';
const unescaped = JSON.parse(input);
// → "Hello\nWorld" (actual newline character)
// Template literals don't need quote escaping
const tpl = `She said "hello"`;
// → 'She said "hello"' — no backslashes needed
// Escape for use inside a RegExp
const query = 'price: $5.00 (USD)';
const safe = query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
// → "price: \\$5\\.00 \\(USD\\)"# Escape with repr() — shows escape sequences
raw = "Line 1\nLine 2\t'quoted'"
print(repr(raw))
# → "Line 1\nLine 2\t'quoted'"
# Raw strings skip escape processing
path = r"C:\Users\name\Documents"
print(path)
# → C:\Users\name\Documents (backslashes kept literal)
# JSON escaping with json module
import json
data = 'He said "hello\nworld"'
escaped = json.dumps(data)
# → '"He said \\"hello\\nworld\\""'
# Unicode escaping
text = "Caf\u00e9" # → "Café"
print(text.encode('unicode_escape').decode())
# → "Caf\\xe9"package main
import (
"fmt"
"strconv"
"encoding/json"
)
func main() {
// strconv.Quote adds escape sequences and wraps in quotes
raw := "Line 1\nLine 2\t\"quoted\""
fmt.Println(strconv.Quote(raw))
// → "\"Line 1\\nLine 2\\t\\\"quoted\\\"\""
// strconv.Unquote reverses it
unescaped, _ := strconv.Unquote(`"hello\nworld"`)
fmt.Println(unescaped)
// → hello
// world
// JSON marshal handles escaping automatically
b, _ := json.Marshal("tabs\there & \"quotes\"")
fmt.Println(string(b))
// → "tabs\there \u0026 \"quotes\""
}# Use $'...' syntax for escape sequences in bash echo $'Line 1\nLine 2\tTabbed' # → Line 1 # Line 2 Tabbed # printf interprets escape sequences printf 'Path: C:\\Users\\name\n' # → Path: C:\Users\name # Use jq to escape a string for JSON echo 'He said "hello"' | jq -Rs . # → "He said \"hello\"\n" # Unescape JSON string with jq echo '"Line 1\\nLine 2"' | jq -r . # → Line 1 # Line 2