Jump to content

Doubts about this example.....


Mxlt

Recommended Posts

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>

 

Link to comment
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 comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...