LanguagesJavaScriptJavaScript Methods for Trimming, Padding, and Extracting Strings

JavaScript Methods for Trimming, Padding, and Extracting Strings content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

JavaScript Tutorial

The JavaScript Methods for Searching Strings tutorial presented the complete list of JavaScript (JS) methods for working with strings, along with detailed explanations of JavaScript’s eight string searching methods. In today’s follow-up web development tutorial, we will be taking a look at methods for trimming, padding, and extracting strings.

You can read the previous part in this series by visiting: JavaScript Method for Searching Strings.

Trimming a String with JavaScript

JS provides three methods for removing whitespace from a string: trim(), trimStart(), and trimEnd(). The trim() method removes whitespace from both ends of a string, while trimStart() and trimEnd() remove whitespace from the beginning and end of a string, respectively.

trim() Method Syntax

All three JS trimming methods operate on the invoking string object instance, so none of them take in any parameters. Here is the syntax for using the trim() methods in Javacript:


trim() Method JavaScript Examples

let str = "  Let's trim some fat! ";
let trimResult = str.trim();
let trimStartResult = str.trimStart();
let trimEndResult = str.trimEnd();

console.log(trimResult, trimStartResult, trimEndResult);
"Let's trim some fat!"
"Let's trim some fat! "
"  Let's trim some fat!"

Note that the trimStart() and trimEnd() methods are an ES2019/ES10 feature and are not supported in Internet Explorer.

Read: Best Online Courses to Learn JavaScript

Padding a String in JavaScript

Unlike trimming, which involves removing whitespace characters, padding methods add a string to another string to a certain length from the start or end of the string and return the resulting string, up to the specified length.

padStart() and padEnd() Syntax

As seen below, the padStart() and padEnd() methods take the same two parameters – targetLength and padString:

string.padStart(targetLength, padString)
string.padEnd(targetLength, padString)
  • targetLength – The length of the final string after the current string has been padded.
  • padString (optional) – The string to pad the current string with. Its default value is ” ” if omitted.

Note that:

  • If padString is too long, it will be truncated to meet targetLength.
  • If targetLength is less than the string length, the original string is returned unmodified.

padStart() and padEnd() Code Examples in JavaScript

Suppose you want a numeric string with 8 characters. For a string whose length is less than 8, it will be padded with zeros (0):

let str = '1234567';
let padStartResult1 = str.padStart(12, '0');
str = 'abcd';  
let padStartResult2 = str.padStart(8);
console.log(padStartResult1, padStartResult2);
"    abcd"
let padEndResult1 = str.padEnd(10);
let padEndResult2 = str.padEnd(10, '*');
let padEndResult3 = str.padEnd(12, 'efg');
console.log(padEndResult1, padEndResult2, padEndResult3);
"abcd      "

How to Extract Strings From Another String in JavaScript

Extracting strings is a task that JavaScript is particularly adept at. To do so, Javascript provides a total of four methods to extract string parts! They are split(), substr(), substring(), and slice(). Each method performs a different type of string extraction so we will cover them individually in the section below.

split() Method in JavaScript

The JavaScript split() method divides a string into a list of substrings and returns them as an array, leaving the original string unchanged.

Syntax of split() Method

The syntax of the split() method in JavaScript is:

string.split(separator, limit)

The split() method accepts the following two optional parameters:

  • separator – The pattern (string or regular expression) describing where each split should occur.
  • limit – A non-negative integer limiting the number of pieces to split the given string into.

substr() / substring() Method in JavaScript

Both the substr() and substring() methods extract parts of the string from a specified position; the difference is that substr() allows developers to specify the number of characters you want to extract, whereas substring() accepts the end position.

Syntax of substr() and substring() Methods

The above difference is reflected in each method’s syntax:

string.substr(start, length)
string.substring(start, end)

In both cases, the start parameter is a number that specifies the starting position from which to copy the substring from the source string. (Note that, in JavaScript, the indexing starts from zero.)

The length parameter is optional and specifies the number of characters to extract.
If omitted, it extracts the rest of the string. Otherwise, if length is 0 or negative, an empty string is returned.

The end parameter is an optional number indicating the end position up to which the substring is copied.

Read: Top Collaboration Tools for Web Developers

slice() Method in JavaScript

The slice() method extracts a part of a string as a new string, while leaving the original string unaltered.

Syntax of the slice() Method

Like the substring() method, slice() also accepts a start and end parameter:

string.slice(start, end)

Again, the start parameter is a number that specifies a zero-indexed starting position from which to copy the substring from the source string.
The end parameter is optional and specifies the end position (up to, but not including).

Differences Between substring() and slice()

While both the substring() and slice() methods let you extract substrings from a string by specifying a start and optional end parameter, they have a couple of key differences that you should to be aware of:

  • Negative Values – with slice(), when you enter a negative number as an argument, slice() counts backward from the end of the string. With substring(), it will treat a negative value as zero.
  • Parameter Consistency – another big difference is that, with substring(), if the 1st argument is greater than the 2nd argument, substring() will swap them whereas slice() will return an empty string.

JavaScript slice() Method Code Examples

let str = "Outside my window there’s an open road";
// Split the words
let splitWords = str.split(" ");
// Split the characters, including spaces
let splitCharacters = str.split("");
// Using the limit parameter
let splitThreeFirstWords = str.split(" ");

console.log(splitWords, splitCharacters, splitThreeFirstWords);
[O,u,t,s,i,d,e, ,m,y, ,w,i,n,d,o,w, ,t,h,e,r,e,’,s, ,a,n, ,o,p,e,n, ,r,o,a,d]

// Extract a substring from text using substr()
let substrResult1 = str.substr(11, 6);
// Extract everything after position 18:
let substrResult2 = str.substr(18);

console.log(substrResult1, substrResult2);
"there’s an open road"

// Extract a substring from text using substring()
let substringResult1 = str.substring(11, 17);
// Extract everything after position 18:
let substringResult2 = str.substring(11, 17);

console.log(substringResult1, substringResult2);
"there’s an open road"

// Slice out the rest of the string
let sliceResult1 = str.slice(18);
// Using a negative start parameter
let sliceResult2 = str.slice(-10);
// Provide both start and end parameters
let sliceResult3 = str.slice(18, 25);
// Using negative start and end parameters
let sliceResult4 = str.slice(-10, -5);

console.log(sliceResult1, sliceResult2, sliceResult3, sliceResult4);
"there’s an open road"
" open road"
" open"

There’s a demo on that contains all of the JavaScript code examples presented here today.

Final Thoughts on JavaScript Methods for Trimming, Padding, and Extracting Strings

In this three part series on JavaScript String methods, we learned how to use trimming, padding, and extracting methods. In the next and final installment, we will be taking a look at the remaining methods of the String object, including those for concatenating and changing case.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories