JavaScript 如何使用转义字符正确记录字符串中的引号

JavaScript 如何使用转义字符正确记录字符串中的引号

转义字符 是用于开始转义命令以执行某些操作的符号。它们是一些可以被解释成与我们打算不同的其他方式的字符。JavaScript使用 **** (反斜杠)作为转义字符。

我们的目标是要在控制台中打印出如下内容:

""Geeks" for "Geeks" is 'the' best 'platform'"

要打印引号,使用转义字符有两个选项:

  • 对于单引号: \’ (反斜杠后跟单引号)
  • 对于双引号: \” (反斜杠后跟双引号)

我们可以在控制台上使用单引号和双引号打印引号,而不使用转义字符。但是有一个限制,我们只能打印单引号或双引号之一。如果字符串用单引号表示,则只能打印双引号,如果字符串用双引号表示,则可以在其中打印单引号。

用单引号或双引号表示的字符串是相同的,没有区别。

示例1: 在这个示例中,我们将在控制台上打印单引号和双引号。

Javascript

// Using single quotes for string
let s1 = 'Geeks for Geeks';
 
// Using double quotes for string
let s2 = "Geeks for Geeks";
 
// Both s1 and s2 are same
console.log((s1 === s2)); // true
console.log(s1); // Geeks for Geeks
console.log(s2); // Geeks for Geeks
 
// Using single quotes to represent string
// and double to represent quotes inside
// string
let str = '"Geeks" "FOR" Geeks';
console.log(str); // "Geeks" "FOR" Geeks
 
// Using double quotes to represent string
// and single to represent quotes in string
str = "'Geeks' 'FOR' Geeks";
console.log(str); // 'Geeks' 'FOR' Geeks

输出结果:

true
Geeks for Geeks
Geeks for Geeks
"Geeks" "FOR" Geeks
'Geeks' 'FOR' Geeks

示例 2: 使用转义序列 – 如果您在引号之前使用了 \’,那么您必须在引号结束时也使用 \’,反之亦然。

Javascript

// Using escape sequences - here you can
// use single as well as double quotes
// within the string to print quotation
let str = 'Geeks \'FOR\' Geeks';
console.log(str); // Geeks 'FOR' Geeks
 
str = "Geeks \"FOR\" Geeks";
console.log(str); // Geeks "FOR" Geeks
 
str = '\'Geeks \"FOR\" Geeks\'';
console.log(str); // 'Geeks "FOR" Geeks'
 
str = "\"\"Geeks\" for \"Geeks\" is \'the\' best \'platform\'\"";
console.log(str); // ""Geeks" for "Geeks" is 'the' best 'platform'"

输出:

Geeks 'FOR' Geeks
Geeks "FOR" Geeks
'Geeks "FOR" Geeks'
""Geeks" for "Geeks" is 'the' best 'platform'"

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程