Techniques for Modifying the Start and End of Strings in JavaScript
In JavaScript, there are several ways to modify the leading and trailing characters from strings. Let's explore some of the most commonly used methods.
1. String.padStart()
method
String.padStart()
method adds characters to the beginning of the string if its length is less than a certain length. It accepts two arguments: the length of the string should be and what string to add if it's not that long. The character to use is optional and defaults to a space.
let hour = "4"; let minute = "10"; let second = "8"; hour.padStart(2, "0"); //"04" minute.padStart(2, "0"); //"10" second.padStart(2, "0"); //"08"
2. String.padEnd()
method
String.padEnd()
method adds characters to the end of the string if smaller than a certain length. It accepts two arguments: the length of the string should be and what string to add if it's not that long. The character to use is optional and defaults to space.
let price1 = "20.50"; let price2 = "100.00"; price1.padEnd(6, "0"); //"20.500" price2.padEnd(6, "0"); //"100.000"
3. String.trim()
method
String.trim()
method removes the leading and trailing white spaces from the string. This method is helpful when you need to get rid of unwanted spaces at the beginning or end of a string.
let str = " I love JS. "; str.trim(); // Returns "I love JS."
4. String concatenation
You can add a string to the beginning or end of another string using the addition operator.
let sentence = "I love JavaScript"; sentence + ", and I love coding with it!"; // Output: "I love JavaScript, and I love coding with it!"
Get my free, weekly JavaScript tutorials
Want to improve your JavaScript fluency?
Every week, I send a new full-length JavaScript article to thousands of developers. Learn about asynchronous programming, closures, and best practices — as well as general tips for software engineers.
Join today, and level up your JavaScript every Sunday!
Thank you, Taha, for your amazing newsletter. I’m really benefiting from the valuable insights and tips you share.