esc_js() WordPress Function

The esc_js() function is used to escape JavaScript strings. It makes sure that the string is properly formatted and that any special characters are escaped. This function is especially important when outputting data that has been entered by users, as it helps to prevent malicious code from being executed.

esc_js( string $text ) #

Escapes single quotes, ", , &, and fixes line endings.


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 ‘js_escape’ filter is also applied here.


Top ↑

Parameters

$text

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


Top ↑

Return

(string) Escaped text.


Top ↑

More Information

See Data Validation for more information on escaping and sanitization.


Top ↑

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


Top ↑

Changelog

Changelog
VersionDescription
2.8.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.

Show More