Jump to content

Doubts about this example.....

Recommended Posts


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>

<h2>JavaScript String.trim()</h2>

<p>IE 8 does not support String.trim(). To trim a string you can use a polyfill.</p>

if (!String.prototype.trim) {
    String.prototype.trim = function () {
    return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
var str = "       Hello World!        ";



Link to post
Share on other sites

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


  • Like 1
  • Thanks 1
Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...