0

For example, I have this php string: "2015-06-26". I want to assign it to a javascript var.

I tried with String("2015-06-26"), but it's substracting the numbers, so the result is this: "1983".

How am I supposed to do it? Thanks.

Manu Mackwar
  • 61
  • 1
  • 6
  • and what is the command that you wrote? – Satya Jul 18 '15 at 00:08
  • possible duplicate of [Parse date without timezone javascript](http://stackoverflow.com/questions/17545708/parse-date-without-timezone-javascript) – shoover Jul 18 '15 at 00:10
  • @shoover This has nothing to do with parsing dates. He's just trying to pass a literal string from PHP to JS. – Barmar Jul 18 '15 at 00:18

2 Answers2

2

Use json_encode() to convert any PHP value to the corresponding Javascript literal:

var datestring = <?php echo json_encode($datestring); ?>;
Barmar
  • 741,623
  • 53
  • 500
  • 612
1

what about that?

var date = '<?php echo str_replace("'", "\'", $yourstring);?>';
Community
  • 1
  • 1
Reflective
  • 3,854
  • 1
  • 13
  • 25
  • On https://stackoverflow.com/questions/6269188/how-do-i-escape-only-single-quotes David M. explains this is subject to code injection: if your string contains \'; and some code then it gets converted to \\'; and some code and date = '\\'; is interpreted as a single character string and the code gets executed. – Arnaud Aug 12 '22 at 11:39