Using WordPress ‘js_escape’ PHP filter

The js_escape WordPress PHP Filter allows you to clean and escape text for output in JavaScript, making sure it is safe to use.

Usage

add_filter('js_escape', 'your_custom_function', 10, 2);
function your_custom_function($safe_text, $text) {
    // your custom code here
    return $safe_text;
}

Parameters

  • $safe_text (string): The text after it has been escaped.
  • $text (string): The text prior to being escaped.

More information

See WordPress Developer Resources: js_escape

Examples

Modify the escaped text

Customize the text after it has been escaped for JavaScript output.

add_filter('js_escape', 'customize_escaped_text', 10, 2);
function customize_escaped_text($safe_text, $text) {
    // Append custom text to the escaped string
    $safe_text .= ' - Custom Text';
    return $safe_text;
}

Replace specific characters

Replace specific characters after the text has been escaped.

add_filter('js_escape', 'replace_specific_characters', 10, 2);
function replace_specific_characters($safe_text, $text) {
    // Replace all occurrences of 'A' with 'B' in the escaped string
    $safe_text = str_replace('A', 'B', $safe_text);
    return $safe_text;
}

Uppercase the escaped text

Change the escaped text to uppercase.

add_filter('js_escape', 'uppercase_escaped_text', 10, 2);
function uppercase_escaped_text($safe_text, $text) {
    // Convert the escaped text to uppercase
    $safe_text = strtoupper($safe_text);
    return $safe_text;
}

Add a prefix to the escaped text

Add a prefix to the escaped text.

add_filter('js_escape', 'add_prefix_to_escaped_text', 10, 2);
function add_prefix_to_escaped_text($safe_text, $text) {
    // Add a prefix to the escaped text
    $safe_text = 'Prefix: ' . $safe_text;
    return $safe_text;
}

Remove numbers from the escaped text

Remove any numbers from the escaped text.

add_filter('js_escape', 'remove_numbers_from_escaped_text', 10, 2);
function remove_numbers_from_escaped_text($safe_text, $text) {
    // Remove numbers from the escaped text
    $safe_text = preg_replace('/[0-9]/', '', $safe_text);
    return $safe_text;
}