函数文档

esc_js()

💡 云策文档标注

概述

esc_js() 是 WordPress 中用于转义文本字符串以在 JavaScript 中安全输出的函数,特别适用于内联 JS(如 HTML 标签属性中的 onclick)。它转义单引号、双引号、& 等特殊字符,并修正换行符。

关键要点

  • 用途:转义文本用于在 JavaScript 中输出,确保安全性和正确性,主要针对内联 JS 场景。
  • 参数:接受一个必需的字符串参数 $text,返回转义后的字符串。
  • 处理内容:转义单引号、双引号、& 字符,并处理换行符( 移除, 转义为 n)。
  • 内部流程:先通过 wp_check_invalid_utf8() 检查无效 UTF-8,再使用 _wp_specialchars() 转义特殊字符,最后应用 stripslashes 和 addslashes 处理。
  • Hook:应用 'js_escape' 过滤器,允许插件修改转义后的字符串。
  • 注意事项:字符串需用单引号包裹;对于非内联 JS 场景,推荐使用 wp_json_encode()。

代码示例

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 ) );
	return apply_filters( 'js_escape', $safe_text, $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.

Parameters

$textstringrequired
The text to be escaped.

Return

string Escaped text.

More Information

See Data Validation for more information on escaping and sanitization.

Source

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

Hooks

apply_filters( ‘js_escape’, string $safe_text, string $text )

Filters a string cleaned and escaped for output in JavaScript.

Changelog

Version Description
2.8.0 Introduced.

User Contributed Notes

  1. Skip to note 3 content

    I don’t really see the value of using esc_js() anymore. If you really have to do an inline script attribute, you may want to consider the following example with wp_json_encode() and esc_attr(), which seems easier to read and maintain:

    
    <input id="subbox" type="text" name="email"
    	value="<?php echo esc_attr( $instance['input_text'] ); ?>"
    	onfocus="<?php echo esc_attr( $onfocus ); ?>"
    	onblur="<?php echo esc_attr( $onblur ); ?>" />

    But in actuality, this specific example doesn’t need any PHP in its script attributes at all. The following should have the same result, thanks to the defaultValue property on the HTMLInputElement interface:

    <input id="subbox" type="text" name="email"
    	value="<?php echo esc_attr( $instance['input_text'] ); ?>"
    	onfocus="if ( this.defaultValue === this.value ) { this.value = ''; }"
    	onblur="if ( '' === this.value ) { this.value = this.defaultValue; }" />

  2. Skip to note 4 content

    Example

    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 = ;