esc_js( string $text )

Escape single quotes, htmlspecialchar ” &, and fix line endings.

Description Description

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.

Parameters Parameters


(string) (Required) The text to be escaped.

Top ↑

Return Return

(string) Escaped text.

Top ↑

Source Source

File: wp-includes/formatting.php

function esc_js( $text ) {
	$safe_text = wp_check_invalid_utf8( $text );
	$safe_text = _wp_specialchars( $safe_text, ENT_COMPAT );
	$safe_text = preg_replace( '/&#(x)?0*(?(1)27|39);?/i', "'", stripslashes( $safe_text ) );
	$safe_text = str_replace( "\r", '', $safe_text );
	$safe_text = str_replace( "\n", '\\n', addslashes( $safe_text ) );
	 * Filter a string cleaned and escaped for output in JavaScript.
	 * Text passed to esc_js() is stripped of invalid or special characters,
	 * and properly slashed for output.
	 * @since 2.0.6
	 * @param string $safe_text The text after it has been escaped.
 	 * @param string $text      The text prior to being escaped.
	return apply_filters( 'js_escape', $safe_text, $text );

Top ↑

Changelog Changelog

Version Description
2.8.0 Introduced.

Top ↑

More Information More Information

See Data Validation for more information on escaping and sanitization.

Top ↑

User Contributed Notes User Contributed Notes

  1. Skip to note content
    Contributed by Codex


    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 JavasSript.

    <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" />

    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. (wp_json_encode() includes the string-delimiting quotes for you):

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

You must log in before being able to contribute a note.