Attention Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

Function Reference/esc js


Escape single quotes, htmlspecialchar " < > &, and fix line endings. Escapes text strings for echoing in JS. It is intended to be used for inline JS (in a tag attribute, for example onclick="…"). Note that the strings have to be in single quotes. The filter ‘js_escape’ is also applied here. If you're not working with inline JS in HTML event handler attributes, a more suitable function to use is wp_json_encode, which is built-in to WordPress.


<?php esc_js$text ?>


(string) (required) Text to escape
Default: None

Return Values

Escaped js string.


Example of an input tag within a form displayed on the front-end of the site, generated from a widget. The first php segment is using esc_attr as it is an html attribute of input, while the next php segments is using esc_js within inline Javascript.

<input type="text" value="<?php echo esc_attr( $instance['input_text'] ); ?>" id="subbox" onfocus="if ( this.value == '<?php echo esc_js( $instance['input_text'] ); ?>') { this.value = ''; }" onblur="if ( this.value == '' ) { this.value = '<?php echo esc_js( $instance['input_text'] ); ?>'; }" name="email" />

As mentioned above, json_encode is suitable if you're not dealing with escaping strings inside of HTML event handler attributes (json_encode includes the string-delimiting quotes for you):

var title = <?php echo json_encode( $instance['title'] ) ?>;

Change Log

Since: 2.8.0

Source File

esc_js() is located in wp-includes/formatting.php


See: Data Validation article for an in-depth discussion of input and output sanitization.

See also index of Function Reference and index of Template Tags.