esc_js()WP 2.8.0

Escapes string for save use in JavaScript. Escape single quotes, htmlspecialchar " < > &, and fix line endings.

Hooks from the function

Return

null. Nothing.

Usage

* @since 1.2.2;

Examples

0

#1 Basic example

$text = "single quote ', double quote \", greater than >, less <, ampersand &";
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.2.2

* @since 1.2.2
*
* @param string $myHTML The text to be converted.
* @return string Converted text.
*/
function htmlentities2( $myHTML ) {
	$translation_table              = get_html_translation_table( HTML_ENTITIES, ENT_QUOTES );
	$translation_table[ chr( 38 ) ] = '&';
	return preg_replace( '/&(?![A-Za-z]{0,4}\w{2,3};|#[0-9]{2,3};)/', '&amp;', strtr( $myHTML, $translation_table ) );
}

/**
* Escapes single quotes, `"`, `<`, `>`, `&`, and fixes 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 {@see 'js_escape'} filter is also applied here.
*
* @since 2.8.0