// 示例代码:处理 JavaScript 中的转义字符
// 1. 使用反斜杠 (\) 转义特殊字符
let str1 = 'This is a string with a single quote (\')';
console.log(str1); // 输出: This is a string with a single quote (')
let str2 = "This is a string with a double quote (\")";
console.log(str2); // 输出: This is a string with a double quote (")
// 2. 使用反斜杠转义其他特殊字符
let str3 = "This is a newline:\nand this is the second line.";
console.log(str3);
// 输出:
// This is a newline:
// and this is the second line.
let str4 = "This is a tab:\tand this is after the tab.";
console.log(str4);
// 输出: This is a tab: and this is after the tab.
// 3. 使用 Unicode 转义序列
let str5 = "\u00A9"; // 版权符号 ©
console.log(str5); // 输出: ©
// 4. 使用十六进制转义序列
let str6 = "\x48\x65\x6C\x6C\x6F"; // Hello
console.log(str6); // 输出: Hello
// 5. 使用 JSON.stringify() 方法自动处理转义字符
let obj = { name: "John", message: "Say \"Hello\"!" };
let jsonString = JSON.stringify(obj);
console.log(jsonString); // 输出: {"name":"John","message":"Say \"Hello\"!"}
\
) 进行转义。\n
) 和制表符 (\t
) 等特殊字符也可以通过反斜杠进行转义。\u
或 \x
来表示 Unicode 或十六进制编码的字符。上一篇:js 分割字符串
下一篇:js 字符转int
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站