esc_js

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

Description

(string) esc_js( (string) $text ); 

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 is also applied here.

Returns (string)

Escaped text.

Parameters (1)

0. $text (string)
The text to be escaped.

Usage

  1. if ( !function_exists( 'esc_js' ) ) { 
  2. require_once ABSPATH . WPINC . '/formatting.php'; 
  3.  
  4. // The text to be escaped. 
  5. $text = ''; 
  6.  
  7. // NOTICE! Understand what this does before running. 
  8. $result = esc_js($text); 
  9.  

Defined (1)

The function is defined in the following location(s).

/wp-includes/formatting.php  
  1. function esc_js( $text ) { 
  2. $safe_text = wp_check_invalid_utf8( $text ); 
  3. $safe_text = _wp_specialchars( $safe_text, ENT_COMPAT ); 
  4. $safe_text = preg_replace( '/&#(x)?0*(?(1)27|39);?/i', "'", stripslashes( $safe_text ) ); 
  5. $safe_text = str_replace( "\r", '', $safe_text ); 
  6. $safe_text = str_replace( "\n", '\\n', addslashes( $safe_text ) ); 
  7. /** 
  8. * Filters a string cleaned and escaped for output in JavaScript. 
  9. * Text passed to esc_js() is stripped of invalid or special characters,  
  10. * and properly slashed for output. 
  11. * @since 2.0.6 
  12. * @param string $safe_text The text after it has been escaped. 
  13. * @param string $text The text prior to being escaped. 
  14. */ 
  15. return apply_filters( 'js_escape', $safe_text, $text );