jQuery html() function and  

886 Views Asked by At

I have a string that contains unicode encoded nonbreaking space. I need to save this string to the hidden HTML element, so another function can read this value.

It looks like html() function does some transformation of the string. Example:

  var testString = "string with \xa0 non breaking space";
  $(".export-file-buffer").html(testString);
  var receivedString = $(".export-file-buffer").html();
  console.log(testString);
  console.log(receivedString);

What I see in console:

string with   non breaking space
string with   non breaking space

Why exactly it's happening? Could you point me to the doc that describes this behavior?

2

There are 2 best solutions below

2
On

Rather than making it displayable, if you just need to store a reference to it on an element you can use the data() method.

var testString = "string with \xa0 non breaking space";
var $target = $('#target');

$target.data('rawData', testString);

console.log($target.data('rawData'));

var fromData = $target.data('rawData');

console.log(
  fromData.split('').map(function(character){
    if (character < ' ' || character > '~' ) {
      return '\\x'+ character.charCodeAt(0).toString(16);
    } else {
      return character;
    }
  }).join('')
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="target"></div>

As you can see, the value is not converted to &nbsp;. The reason for this is that when jQuery sets a value on an Element with data() it does not put it directly on the element. Rather, it stores the value in an internal cache and associates the value to the element. Since the value is only in javascript memory, the browser does not convert it.

The value still prints out in the console not as \xa0 because that hex character code reference is not a visible character code on the ascii chart. I included a little script that encodes the characters on the ascii chart before space and after the tilde.

0
On

There are multiple ways of keeping string that can be shared on a html page.

  1. Using input type="hidden". Here you can simply keep value by $(".export-file-buffer").val(testString) just like you did for html
  2. (less recommended) Using a global variable/ keeping on window. window.export-file-buffer = testString and retrieve later calling window.export-file-buffer