What is the importance of str.padStart() method in JavaScript?

JavascriptObject Oriented ProgrammingFront End Technology

We can attach two strings using the concat() method. But if we need to attach a specific string at the starting of the first string then the easiest way is string.padStart(). This method not only adds the second string at the start of the first string but also looks after the number of characters to be added. It basically takes two parameters one is the length and the other is second string. The method string.padStart() add the second string to the first based on the length provided to it.

syntax

string.padStart(length,"string");

It takes the length as the parameter to concise the resulted string to those many characters.

It takes another string to attach it to the provided string.

Example

Live Demo

<html>
<body>
   <script>
      var str = "the best";
      var st = "Hello"
      document.write(st.padStart(24," glad to meet you, "));
      document.write("</br>");
      document.write(str.padStart(16, "Tutorix "));
   </script>
</body>
</html>

Output

glad to meet you, Hello
Tutorix the best

When the first string is more in size than the length provided, then no changes will take place to the original string and that original string will be displayed as the output. 

Example

Live Demo

<html>
<body>
<script>
   var str = "Tutorix is the best e-learning platform best";
   document.write(str.padStart(16, "Tutorix "));
</script>
</body>
</html>

Output

Tutorix is the best e-learning platform best
raja
Published on 16-Jul-2019 10:28:44
Advertisements