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.

2
  • 1
    Does this answer your question? Put quotes around a variable string in JavaScript Commented Dec 21, 2019 at 15:40
  • 1
    How did it not solve your question? Could you go into more detail about what you attempted Commented Dec 21, 2019 at 15:48

5 Answers 5

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!

Sign up to request clarification or add additional context in comments.

Comments

1

You can use template literals

const today = new Date();
const year = today.getFullYear();
const yearWithQuotes = `"${year}"`
console.log(yearWithQuotes)

Comments

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)

1 Comment

But then we can just do "“"+year+"”" ^^
0

you can cast by doing year = year + ""

Comments

0
function loadCopyrightText() {
  var today = new Date();
  return today.getFullYear().toString();
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.