0

So, I was making the footer for my website just now and I wanted to make the year shown on the footer always be the current year. I need to use JavaScript, so I wrote some code for it:

function loadCopyrightText() {
  var today = new Date();
  var year = today.getFullYear();
}

But now I have a problem. I want to show the variable year as a string like this:

“2019”

I researched the Number.toString() method and it did not solve the problem.

FZs
  • 16,581
  • 13
  • 41
  • 50
  • 1
    Does this answer your question? [Put quotes around a variable string in JavaScript](https://stackoverflow.com/questions/9714759/put-quotes-around-a-variable-string-in-javascript) – Anurag Srivastava Dec 21 '19 at 15:40
  • 1
    How did it not solve your question? Could you go into more detail about what you attempted – Mike Dec 21 '19 at 15:48

5 Answers5

2

I like template literals, especially this is a good case for that.

As the documentation states:

Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them. They were called "template strings" in prior editions of the ES2015 specification.

You can do something like this:

const getCurrentYear = () => new Date().getFullYear();
const copyrightText = `© ${getCurrentYear()} All Rights Reserved`;
console.log(copyrightText);

Or if you want to keep the double quotes as in your question, you can do the following:

const getCurrentYear = () => new Date().getFullYear();
const copyrightText = `© “${getCurrentYear()}” All Rights Reserved`;
console.log(copyrightText);

I hope this helps!

norbitrial
  • 14,716
  • 7
  • 32
  • 59
1

You can use template literals

const today = new Date();
const year = today.getFullYear();
const yearWithQuotes = `"${year}"`
console.log(yearWithQuotes)
Dan Starns
  • 3,765
  • 1
  • 10
  • 28
1

You can use String as a function (not as a constructor i.e. without the new keyword) to coerce your element to a string.

const today = new Date();
const year = today.getFullYear();
 
const stringified = '“'+String(year)+'”'
console.log(stringified)
console.log(typeof stringified)
Ivan
  • 34,531
  • 8
  • 55
  • 100
0

you can cast by doing year = year + ""

Nicolas Busca
  • 1,100
  • 7
  • 14
0
function loadCopyrightText() {
  var today = new Date();
  return today.getFullYear().toString();
}
AlpSenel
  • 190
  • 1
  • 12