I have the following code in the javascript which outputs the date(s). With backslash for that, I'm replacing those strings with the str_replace to remove backslash, but I can't sanitize that using any escaping function like esc_js.

Stored Days Array

array (size=2)
  0 => string '4/7/2018' (length=8)
  1 => string '11/18/2017'(length=10)

The code

var disabledDays = <?php echo str_replace( '\\/', '/', wp_json_encode( $iva_disable_days ) ); ?>;

Tried Code which is not working

var disabledDays = <?php echo esc_js( str_replace( '\\/', '/', wp_json_encode( $iva_disable_days ) ) ); ?>;

Result Output

var disabledDays = [&quot;4/7/2018&quot;,&quot;11/18/2017&quot;];

How do I sanitize the above section in The Code

1 Answer 1


esc_js() is intended for escaping data for use within an HTML attribute.

If you want to escape data for use within an inline script, wp_json_encode() should be sufficient.

For example:

var disabledDays = <?php echo wp_json_encode( $iva_disable_days ); ?>;

This outputs:

var disabledDays = ["4\/7\/2018","11\/18\/2017"];

If you check the variable in your dev tools console, you will see that it is being parsed correctly:

enter image description here

However - if you absolutely do not want escaped slashes (not recommended), the second param to wp_json_encode() is a bitmask of options:

var disabledDays = <?php echo wp_json_encode( $iva_disable_days, JSON_UNESCAPED_SLASHES ); ?>;

This outputs:

var disabledDays = ["4/7/2018","11/18/2017"];

For a list of available options, check the PHP json_encode() docs.

  • Removed the str_replace and worked with the encoding by the supplied options JSON_UNESCAPED_SLASHES
    – Maqk
    Oct 6, 2017 at 9:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.