-1

I'm not sure what's the best way to word this question but basically I'm working on my second Javascript project to build a Random Quote Generator when I noticed there's some syntax issues on my third quote (please see first screenshot) when my strings include words like "don't" or "can't". I'm not sure if it's because I wrote my strings as '"quote" - author' but this person on Youtube (please see second screenshot) wrote his strings using the same format but hadn't had any syntax issue.

Screenshot1

Screenshot2

Daniel
  • 3
  • 2
  • 2
    [Please do not upload images of code/data/errors.](//meta.stackoverflow.com/q/285551) – Michael M. Jan 13 '23 at 02:58
  • 1
    Just add a backslash (escape character) before the `'` character? In the second picture he's using an alternate apostrophe (not `'`) but similar. – John Smith Jan 13 '23 at 03:02

3 Answers3

4

All of the above lines are allowed in JavaScript:

// delimiter: double quotes
// don't need to escape single quotes
// must escape double quotes
const s1 = "a 'test' a";     
const s2 = "a \"test\" a";

// delimiter: single quotes
// must escape single quotes
// don't need to escape double quotes
const s3 = 'a \'test\' a';
const s4 = 'a "test" a';

// delimiter: grave accent (template literal)
// don't need to escape double quotes
// neither single quotes
const s5 = `a 'test' a`;
const s6 = `a "test" a`;

// string interpolation
const n = 10;
const s7 = `n value is ${n}`;  // evaluates to: n value is 10

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String

davidbuzatto
  • 9,207
  • 1
  • 43
  • 50
  • Interesting. In all my years of JavaScript I did not know about the grave accent. – John Smith Jan 13 '23 at 03:06
  • 1
    @JohnSmith it's used for string interpolation and tagged templates. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals – davidbuzatto Jan 13 '23 at 03:11
2

Using the Escape Character () "Then he said, "Hello, World!""

let quote = "Then he said, \"Hello, World!\"";
Hugo
  • 21
  • 2
0

You can use backticks instead of quotation mark :

const str = "hello "people" from Africa" // wrong way

const correctStr = `hello people from "some country name " and "another" ` //coorect way
Eisa Rezaei
  • 528
  • 1
  • 12