Using WordPress ‘js_escape()’ PHP function

The js_escape() WordPress PHP function escapes single quotes, special character double quotes, and fixes line endings.

Usage

echo js_escape($text_to_escape);

Input:

$text_to_escape = "I'm a 'developer' and I \"love\" coding.";

Output:

I'm a 'developer' and I "love" coding.

Parameters

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

More information

See WordPress Developer Resources: js_escape

Examples

Escaping text for JavaScript output

Escape text to be safely used within a JavaScript string.

$text = "I'm a 'developer' and I \"love\" coding.";
$escaped_text = js_escape($text);
echo "alert('$escaped_text');"; // JavaScript code with escaped text

Escaping text for a JSON object

Escape text to be included in a JSON object.

$name = "John's \"Pizza\" Shop";
$escaped_name = js_escape($name);
echo '{"business_name": "' . $escaped_name . '"}'; // JSON object with escaped text

Escaping text for use in an HTML attribute

Escape text to be safely used within an HTML attribute.

$tooltip = 'Click "here" to submit the form.';
$escaped_tooltip = js_escape($tooltip);
echo '<button title="' . $escaped_tooltip . '">Submit</button>'; // Button with escaped tooltip

Escaping text with newlines

Escape text with newlines to be safely used within a JavaScript string.

$text = "Line 1\nLine 2";
$escaped_text = js_escape($text);
echo "console.log('$escaped_text');"; // JavaScript code with escaped text and preserved newlines

Escaping user-generated content

Escape user-generated content to prevent XSS attacks when displaying it within a JavaScript string.

$user_comment = "I \"love\" this 'article'!";
$escaped_comment = js_escape($user_comment);
echo "alert('New comment: $escaped_comment');"; // Alert with escaped user-generated content