Using WordPress ‘esc_js()’ PHP function

The esc_js() WordPress PHP function escapes text strings for use in JavaScript. It’s especially handy for inline JavaScript, like in tag attributes (e.g., onclick=”…”). The function ensures text strings are safe to use in these contexts by escaping special characters like single quotes, double quotes, the ampersand, and line endings. Also, this function applies the ‘js_escape’ filter.

Usage

Here’s a simple way to use the esc_js() function. Assume we have a form input that needs some inline JavaScript for an onfocus event:

<input type="text" value="Enter your email..." id="subbox" 
onfocus="if ( this.value == 'Enter your email...') { this.value = ''; }" 
onblur="if ( this.value == '' ) { this.value = 'Enter your email...'; }" 
name="email" />

In this case, we can use the esc_js() function to escape the preset input value:

<input type="text" value="Enter your email..." id="subbox" 
onfocus="if ( this.value == '<?php echo esc_js('Enter your email...'); ?>') { this.value = ''; }" 
onblur="if ( this.value == '' ) { this.value = '<?php echo esc_js('Enter your email...'); ?>'; }" 
name="email" />

Parameters

  • $text (string): The text to be escaped.

More information

See WordPress Developer Resources: esc_js()
While esc_js() is not deprecated, some developers suggest using wp_json_encode() and esc_attr() for better readability and maintainability.

Examples

Using esc_js() with an input form for an email field

<input type="text" value="Enter your email..." id="emailInput" 
onfocus="if ( this.value == '<?php echo esc_js('Enter your email...'); ?>') { this.value = ''; }" 
onblur="if ( this.value == '' ) { this.value = '<?php echo esc_js('Enter your email...'); ?>'; }" 
name="email" />

In this code, esc_js() is used to escape the default input value for the email field.

Using esc_js() in a button’s onclick event:

<button onclick="alert('<?php echo esc_js('Button clicked!'); ?>')">Click me</button>

This code will display an alert with the message ‘Button clicked!’ when the button is clicked.

Using esc_js() to escape a JavaScript variable:

<script>
var message = '<?php echo esc_js('Hello, world!'); ?>';
alert(message);
</script>

This code will create a JavaScript variable, escape it with esc_js(), and then display it in an alert.

Using esc_js() in a JavaScript function:

<script>
function sayHello(name) {
    alert('Hello, ' + '<?php echo esc_js(name); ?>');
}
</script>

This code will create a function that takes a name, escapes it using esc_js(), and uses it in an alert.