Mxlt 0 Posted July 16, 2018 Report Share Posted July 16, 2018 Hi! I was going through the JavaScript Tutorial but I bumped into this code that got me so confused...if anybody could explain it to me I would really appreciate it! I am specially confused with the prototype thing, and then those weird codes: after the replace. <!DOCTYPE html> <html> <body> <h2>JavaScript String.trim()</h2> <p>IE 8 does not support String.trim(). To trim a string you can use a polyfill.</p> <script> if (!String.prototype.trim) { String.prototype.trim = function () { return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''); }; var str = " Hello World! "; alert(str.trim()); </script> </body> </html> Quote Link to post Share on other sites
Ingolme 1,035 Posted July 16, 2018 Report Share Posted July 16, 2018 By changing the prototype of a data type, you change every single object of that type. In this example, they are changing the prototype of the String object so that all strings have a trim() method. The trim() method removes spaces from the beginning and end of a string. The code you see in the replace() method /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g is called a regular expression, it is used to do complex manipulations with strings. There is a tutorial page about regular expressions here: https://www.w3schools.com/js/js_regexp.asp 1 1 Quote Link to post Share on other sites
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.