esc_js()WP 2.8.0

Escapes string for save use in JavaScript. 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 js_escape filter is also applied here.

Hooks from the function

Returns

String. Escaped text.

Usage

esc_js( $text );
$text(string) (required)
The text to be escaped.

Examples

0

#1 Basic example

$text = <<<'TEXT'
single quote ', double quote ", greater than >, less <, ampersand &
TEXT;

echo esc_js( $text );

// return: single quote \', double quote &quot;, greater than &gt;, less &lt;, ampersand &amp;
0

#2 Real life example

esc_attr() escapes string for use in an attribute; esc_js() escapes string for use in JS.

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

Changelog

Since 2.8.0 Introduced.

esc_js() code WP 6.8.1

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 ) );
	/**
	 * Filters 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 );
}