search
HomeWeb Front-endJS TutorialJavaScript string prototype properties

JavaScript 字符串原型属性

In JavaScript, each object has its own properties, and each object contains the prototype attribute. A string is also an object in JavaScript. Therefore, it also contains prototype properties.

Prototype properties are nested within objects, which means that each prototype property contains another prototype property. The prototype properties of a string object contain default methods and properties. However, developers can customize prototype properties and add methods and properties to the string prototype.

In this tutorial, we will learn how to use string prototype properties and customize them.

grammar

Users can add any method to the string prototype property according to the following syntax.

String.prototype.method_name = function () {
   // function code
};

In the above syntax, method_name should be the name of the method we want to add to the string prototype.

Example 1 (using toUpperCase() and toLowerCase() methods)

In the following example, we use the toUpperCase() and toLowerCase() methods of the string prototype property to convert the string to uppercase and lowercase respectively.

In the output, the user can observe the resulting string.

<html>
<body>
   <h3 id="Using-the-i-toUpperCase-and-toLowerCase-i-methods-of-string-prototype-property-to-customize-the-strings"> Using the <i> toUpperCase() and toLowerCase() </i> methods of string prototype property to customize the strings </h3>
   <div id = "output"> </div>
   <script>
      let output = document.getElementById("output");
      var str = "Hello readers! This string contains uppercase and lowerCase letters.";
      var res = str.toUpperCase();
      var res1 = str.toLowerCase();
      output.innerHTML = "Original string: " + str + "<br>" + "Uppercase string: " + res + "<br>" + "Lowercase string: " +
      res1;
   </script>
</body>
</html>

Example 2 (using the Length property)

In the following example, we demonstrate how to use the default properties of the string prototype property. Here we use the "length" property to count the total number of characters in the string.

In the output, we can see the total number of characters or length of the string that we calculated using the length property.

<html>
<body>
   <h3 id="Using-the-i-length-i-property-of-the-string-prototype-property-to-get-the-length-of-the-string"> Using the <i> length </i> property of the string prototype property to get the length of the string </h3>
   <div id = "output"> </div>
   <script>
      let output = document.getElementById("output");
      let string = "JavaScript string contains prototype property.";
      let len = string.length;;
      output.innerHTML = "The original string is: " + string + "<br><br>";
      output.innerHTML += "The length of the string is: " + len;
   </script>
</body>
</html>

Example 3 (Adding methods to the string prototype)

We can also add custom methods to string prototype properties. Here, we have added the countWords() property in the string prototype, which counts the total number of words in the string and returns its value.

Here, we split the string using "" as delimiter and calculate the length of the resulting array to calculate the total number of words in the string. In the code, we can see that we can execute the countWords() method with any string as a reference just like other string methods.

<html>
<body>
   <h3 id="Adding-the-i-countWords-method-to-the-i-string-prototype-property"> Adding the <i> countWords() method to the </i> string prototype property </h3>
   <div id = "output"> </div>
   <script>
      let output = document.getElementById("output");
      // adding countWords() method to string prototype property.
      String.prototype.countWords = function () {
      return this.split(" ").length;
      };
      let string1 = "This is a string";
      let string2 = "Hey, do you know how many words are there in this string?";

      output.innerHTML = "The number of words in the string '" + string1 + "' is " + string1.countWords() + "<br>";
      output.innerHTML += "The number of words in the string '" + string2 + "' is " + string2.countWords();
   </script>
</body>
</html>

Example 4 (Default method of custom string prototype)

In this example, we demonstrate how to customize the default method of the string prototype. Here, we have customized the toUpperCase() method. Generally, the toUpperCase() method returns a string after converting all string characters to uppercase.

We have customized it to return the string after converting only the first character to uppercase. Here, we will return the same string if the first character is already uppercase. Otherwise, we convert the first character to uppercase using the ASCII value.

In the output, we can see that the toUpperCase() method only converts the first character of the string to uppercase instead of the entire string.

<html>
<body>
   <h3 id="Customizing-the-i-toUpperCase-method-of-the-i-string-prototype-property"> Customizing the <i> toUpperCase() method of the </i> string prototype property </h3>
   <div id = "output"> </div>
   <script>
      let output = document.getElementById("output");
      
      //  Customizing the toUpperCase() method of the string prototype property to capitalize only the first character
      String.prototype.toUpperCase = function () {
         if (this.charCodeAt(0) >= 97 && this.charCodeAt(0) <= 122) {
         
            // convert to uppercase
            let ascii = this.charCodeAt(0) - 32;
            return String.fromCharCode(ascii) + this.slice(1);
         } else {
            return this;
         }
      }
      let str = "first letter of this string should be capitalized";
      output.innerHTML = "Original string: " + str + "<br>" + "Capitalized string: " + str.toUpperCase();
   </script>
</body>
</html>

Users learned to use string prototype properties. We can use it to add methods and properties to string objects. Additionally, we can use it to customize string properties and methods. After adding the method to the string prototype, we can call the method using the string as a reference.

The above is the detailed content of JavaScript string prototype properties. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
Replace String Characters in JavaScriptReplace String Characters in JavaScriptMar 11, 2025 am 12:07 AM

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

Build Your Own AJAX Web ApplicationsBuild Your Own AJAX Web ApplicationsMar 09, 2025 am 12:11 AM

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

10 jQuery Fun and Games Plugins10 jQuery Fun and Games PluginsMar 08, 2025 am 12:42 AM

10 fun jQuery game plugins to make your website more attractive and enhance user stickiness! While Flash is still the best software for developing casual web games, jQuery can also create surprising effects, and while not comparable to pure action Flash games, in some cases you can also have unexpected fun in your browser. jQuery tic toe game The "Hello world" of game programming now has a jQuery version. Source code jQuery Crazy Word Composition Game This is a fill-in-the-blank game, and it can produce some weird results due to not knowing the context of the word. Source code jQuery mine sweeping game

How do I create and publish my own JavaScript libraries?How do I create and publish my own JavaScript libraries?Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

jQuery Parallax Tutorial - Animated Header BackgroundjQuery Parallax Tutorial - Animated Header BackgroundMar 08, 2025 am 12:39 AM

This tutorial demonstrates how to create a captivating parallax background effect using jQuery. We'll build a header banner with layered images that create a stunning visual depth. The updated plugin works with jQuery 1.6.4 and later. Download the

Getting Started With Matter.js: IntroductionGetting Started With Matter.js: IntroductionMar 08, 2025 am 12:53 AM

Matter.js is a 2D rigid body physics engine written in JavaScript. This library can help you easily simulate 2D physics in your browser. It provides many features, such as the ability to create rigid bodies and assign physical properties such as mass, area, or density. You can also simulate different types of collisions and forces, such as gravity friction. Matter.js supports all mainstream browsers. Additionally, it is suitable for mobile devices as it detects touches and is responsive. All of these features make it worth your time to learn how to use the engine, as this makes it easy to create a physics-based 2D game or simulation. In this tutorial, I will cover the basics of this library, including its installation and usage, and provide a

Auto Refresh Div Content Using jQuery and AJAXAuto Refresh Div Content Using jQuery and AJAXMar 08, 2025 am 12:58 AM

This article demonstrates how to automatically refresh a div's content every 5 seconds using jQuery and AJAX. The example fetches and displays the latest blog posts from an RSS feed, along with the last refresh timestamp. A loading image is optiona

How do I optimize JavaScript code for performance in the browser?How do I optimize JavaScript code for performance in the browser?Mar 18, 2025 pm 03:14 PM

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.