JavaScript子串返回错误

问题描述:

I am using Joomla and attempting to use the substring() function to pull out the first 4 characters of my string. The issue I am having is that I get an error of

This is my syntax - how should I change it so that it functions in my Joomla set-up?

Uncaught TypeError: phpdate.substring is not a function

Here is syntax:

<?php
  $randardate = '20160301';
?>
<script>
  var phpdate = <?php echo $randardate; ?>;
  var yearfromphpdate = phpdate.substring(0,4);
</script>

我正在使用Joomla并尝试使用 substring() code>函数来取出 我的字符串的前4个字符。 我遇到的问题是我收到错误 p>

这是我的语法 - 如何更改它以使其在我的Joomla设置中起作用? p>

未捕获的TypeError:phpdate.substring不是函数 p> blockquote>

这是语法: p> &lt;?php $ randardate ='20160301'; ?&gt; &lt; script&gt; var phpdate =&lt;?php echo $ randardate; ?&gt ;; var yearfromphpdate = phpdate.substring(0,4); &lt; / script&gt; code> pre> div>

Since you are pre processing a javascript file with PHP, without quotes your javascript file would look something like

var phpdate = 20160301;

You need to add quotations like this

var phpdate = '<?php echo $randardate; ?>';

So that when PHP is done processing your file, it will be a string, not an int.

var phpdate = '20160301';

Your stacktrace is being thrown because substring expects a string, not an int.

Add quotation to make phpdate a string.

var phpdate = '<?php echo $randardate; ?>';