简体   繁体   中英

What does this do and can I achieve the same with vanilla JavaScript?

Here's the code:

$('<div/>').text($.trim(myId.val())).html();

I get that myId is a jQuery object, and I'm getting the value. I get that the value is being trimmed.

I suspect a random jQuery div object is being created, given the trimmed value from myId and then having done this, gotten back again by the html() method. The end result is some kind of formatted version of the value from myId .

The question is why? Is there any way to achieve the same using vanilla JavaScript?


EDIT: Really appreciating the insights. My bad form here adding a coda, but does this achieve the same?

goog.string.htmlEscape(goog.string.trim(goog.dom.forms.getValue(myId)));

It is called Html-encoding , and here these are your Vanilla JavaScript alternatives:

function htmlEncode(text) {
    var encodedText = text.replace(/&/g, '&amp;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#39;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;');
    return encodedText;
}

you can also can do it with a similar approach like:

function htmlEncode(text) {
    var txtNode = document.createTextNode(text);
    var txtdiv = document.createElement('div');
    txtdiv.appendChild(txtNode);
    return txtdiv.innerHTML;
};

What this does is HTML escapes the value of myId.val() , removing any leading and trailing whitespace.

As you already noted, $.trim(myId.val()) just removes any leading and trailing whitespace.

It sets a "dummy" div with the text value of $.trim(myId.val()) , which means that it is the literal value of it (no HTML escapes).

When you call .html() on a jQuery element with no arguments, you get back the HTML escaped value of the child nodes (in this instance, the text you just inserted). For example, in HTML ampersands have special meaning as character escapes, so a literal ampersand needs to be represented in an escaped form ( &amp; ).

Using plain JavaScript, this would be equivalent to the following:

var myId = document.getElementById('myid');
var a = document.createElement('div');

// probably an input field, original code uses val()
a.textContent = myId.value.trim();
console.log(a.innerHTML);

Note that String.prototype.trim is an ES5 method, which means that older browsers (such as IE8 and older) may not this method natively. Also, textContent isn't cross-browser. In case of that, you could do this instead:

function trimString(arg) {
  var str = String(arg);
  return str.match(/[\x09-\x0D\x20\xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF]*([\s\S]*?)[\x09-\x0D\x20\xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF]*/)[1];
}

var myId = document.getElementById('myid');
var a = document.createElement('div');

// probably an input field, original code uses val()
var genericText = document.documentElement.textContent ? 'textContent' : 'innerText';
a[genericText] = trimString(myId.value);
console.log(a.innerHTML);

That code gets you the HTML-encoded version of the value of myId

If the value of myId is "<hello>" , the above code returns "&lt;hello&gt;"

The same in vanilla JS would look like:

var elem = document.createElement('div');
elem.innerText = myId.value; // set as TEXT
console.log(elem.innerHTML); // get as HTML

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM