Daniel
Daniel

Reputation: 3

Javascript - How to add strings with quotation marks inside a quotation mark?

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

Upvotes: -1

Views: 656

Answers (3)

Eisa Rezaei
Eisa Rezaei

Reputation: 553

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

Upvotes: 0

davidbuzatto
davidbuzatto

Reputation: 9424

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

Upvotes: 4

Hugo
Hugo

Reputation: 41

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

let quote = "Then he said, \"Hello, World!\"";

Upvotes: 2

Related Questions