WordPress stripping away backslashes from HTML

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.

script
$(document).ready(function(){
$("input#MobileNo").on({
  keydown: function(e) {
    if (e.which === 32)
      return false;
  },
  change: function() {
    this.value = this.value.replace(/\s/g, "");
   }
 });

 });
/script

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.

Topic escaping plugins Wordpress

Category Web


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().

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.