Hi I'm kind of new to WordPress. I have come across this issue lately when running my webpages from my WordPress server.

I have this piece of code that clears any white spaces in the text input field. But after uploading it to the server directory, the backslashes in that peice of code is stripped away. The same happens to js file as well. Due to this I'm unable to use the js \n character at all.

  keydown: function(e) {
    if (e.which === 32)
      return false;
  change: function() {
    this.value = this.value.replace(/\s/g, "");


Any idea how to fix this. I have read that esc_js() can be used, but don't know how.

WordPress is great and secure and hence I want to learn it.

  • Just answered your question on esc_js(). Can you elaborate on what you were trying to achieve with your JavaScript code above? Are all your concerns captured in my response below? – nyedidikeke Feb 18 '17 at 12:38
  • The JavaScript code mentioned above, is in the HTML code. The function of the code is to remove whitespaces a in a input field. But when the file is uploaded to the WordPress server, the this.value = this.value.replace(/\s/g, ""); gets changed to this.value = this.value.replace(/s/g, ""); ... Due to this the code does not work. So if I have to use esc_js(), whats the syntax in this situation. Thanks in advance. – Coding Enthusiast Feb 18 '17 at 13:53

esc_js() is used to escape single quotes, htmlspecialchar " < > &, and fix line endings; it takes only a single required parameter as a string: the text to be escaped, and returns an escaped text.

It is intended to be used for inline JavaScript such as the onclick="" attribute (note that the strings have to be in single quotes). The 'js_escape' filter is also applied here.

In practice, using the esc_js() function is quite simple and is encouraged for sanity of data.

Let's take a look at its usage in the example below;

Instead of simply echoing a variable as in <?php echo $variable; ?> for an onclick="" attribute when using inline JavaScript, you should leverage on the esc_js() function and as such, you should instead do this: <?php echo esc_js( $variable ); ?>.

So: use (good)

<a href="/news/" onclick="alert( '<?php echo esc_js( $variable ); ?>' )"></a>

instead of (bad)

<a href="/news/" onclick="alert( '<?php echo $variable; ?>' )"></a>

Introduced in version 2.8.0 and defined in wp-includes/formatting.php, the esc_js() related Functions include: esc_sql(), esc_url(), esc_html(), esc_attr(), fetch_rss().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.