By using this site, you agree to the Privacy Policy and Terms of Use.
Accept
Daily News Circuit
  • Home
  • World
    Entertainment

    Selective: Rep. George Santos Expelled From Congress – Daily News Circuit

    By admin 2 Min Read
    Health

    Selective: How Do Drug Formularies Work? – Daily News Circuit

    By admin December 1, 2023
    Healthy Food

    Selective: December Cooking Challenge – WellPlated.com – Daily News Circuit

    By admin December 1, 2023
  • Technology
    Health

    Selective: How Do Drug Formularies Work? – Daily News Circuit

    #Drug #Formularies #Work Your health insurance plan includes a list called a…

    By admin 7 Min Read
    Healthy Food
    Selective: December Cooking Challenge – WellPlated.com – Daily News Circuit
    Insider
    Selective: Lighthouse staff agree pay rise of up to 15% – Daily News Circuit
    Science
    Selective: World must prepare for frequent and severe droughts, report warns – Daily News Circuit
    Technology
    Selective: 8 authors and their 8 gift book picks for this holiday season – Daily News Circuit
  • Insider

    “Rowan Glen Revitalized: Yoghurt Maker Returns with Management Buyout”.

    #Yoghurt #maker #Rowan #Glen #starts #production #management #buyout New boss vows 'We will start small and…

    By admin

    Court Upholds Right to Keep Edinburgh Strip Clubs Open

    #Ban #Edinburgh #strip #clubs #quashed #court The measures were due to come into force in April,…

    By admin

    “Record-Breaking £6 Billion in Scotch Whisky Exports Defies Domestic Challenges”

    #Scotch #whisky #exports #billion #time #domestic #headwinds Meanwhile, Scottish salmon was UK’s biggest food export during…

    By admin

    “Unwinding of Regulations on Al Fresco Seating Anticipated by Late March!”

    #Relaxation #rules #outdoor #seating #expected #March The changes have all been backed in a consultation by…

    By admin

    “A Bright Future Ahead: Construction of 30 New Council Houses in East Lothian Begins!”

    #Construction #council #houses #East #Lothian #underway The development is scheduled for completion towards the end of…

    By admin

    “Glasgow Apprentice Contestant Forced to Exit Show Amidst Health Crisis”

    #Glasgow #Apprentice #contestant #leaves #show #due #health #issues He becomes the second contestant to quit this…

    By admin

    “A New Era: Expro Announces Acquisition of DeltaTek Global”

    #Expro #acquires #DeltaTek #Global The deal should help with the Aberdeen-based company's international growth plans

    By admin

    The UK Narrowly Escapes Recession as Economy Flatlines at 2022’s End

    #narrowly #avoids #recession #economy #flatlines When counting to two decimal places, the UK managed 0.01% growth…

    By admin
  • My Bookmarks
Reading: Unleashing the Power of String Manipulation: Trimming, Extracting, and Padding!
Sign In
  • Join US
Daily News CircuitDaily News Circuit
Aa
  • Bussiness
  • The Escapist
  • Entertainment
  • Science
  • Technology
  • Insider
Search
  • Home
  • Categories
    • Technology
    • Entertainment
    • The Escapist
    • Insider
    • Bussiness
    • Science
    • Health
  • Bookmarks
    • Customize Interests
    • My Bookmarks
  • More DNC
    • Blog Index
    • Sitemap
Have an existing account? Sign In
Follow US
© Daily News Circuit. 2023. All Rights Reserved.
Daily News Circuit > Blog > Technology > Software > Unleashing the Power of String Manipulation: Trimming, Extracting, and Padding!
Software

Unleashing the Power of String Manipulation: Trimming, Extracting, and Padding!

admin
Last updated: 2023/02/14 at 1:22 AM
By admin 9 Min Read
Share
SHARE

#Trimming #Extracting #Padding #Strings

Contents
Trimming a String with JavaScripttrim() Method Syntaxtrim() Method JavaScript ExamplesPadding a String in JavaScriptpadStart() and padEnd() SyntaxpadStart() and padEnd() Code Examples in JavaScriptHow to Extract Strings From Another String in JavaScriptsplit() Method in JavaScriptSyntax of split() Methodsubstr() / substring() Method in JavaScriptSyntax of substr() and substring() Methodsslice() Method in JavaScriptSyntax of the slice() MethodDifferences Between substring() and slice()JavaScript slice() Method Code ExamplesFinal Thoughts on JavaScript Methods for Trimming, Padding, and Extracting Strings

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:

string.trim()
string.trimStart()
string.trimEnd()

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);
/*
Outputs:
"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);
/*
Outputs:
"000001234567"
"    abcd"
*/
let padEndResult1 = str.padEnd(10);
let padEndResult2 = str.padEnd(10, '*');
let padEndResult3 = str.padEnd(12, 'efg');
console.log(padEndResult1, padEndResult2, padEndResult3);
/*
Outputs:
"abcd      "
"abcd******"
"abcdefgefgef"
*/

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);
/*
Outputs:
[Outside,my,window,there’s,an,open,road]
[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]
[Outside,my,window]
*/

// 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);
/*
Outputs:
"window"
"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);
/*
Outputs:
"window"
"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);
/*
Outputs:
"there’s an open road"
" open road"
"there’s"
" open"
*/

There’s a demo on codepen.io 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.

You Might Also Like

Selective: People on the Move in Tech in November – Daily News Circuit

Selective: AWS launches SaaS Quick Launch for easier deployment of SaaS apps – Daily News Circuit

Selective: The promise of generative AI in low-code, testing – Daily News Circuit

Selective: Despite layoffs, software engineering and quality assurance skills remain in-demand – Daily News Circuit

Selective: A guide to low-code vendors that incorporate generative AI capabilities – Daily News Circuit

TAGGED: Extracting, Manipulation, Padding, Power, String, Trimming, Unleashing
admin February 14, 2023
Share this Article
Facebook Twitter Email Copy Link Print
What do you think?
Love0
Sad0
Happy0
Sleepy0
Angry0
Dead0
Wink0
Leave a comment

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Follow US

Find US on Social Medias

Facebook
Like

Twitter
Follow

Youtube
Subscribe

Telegram
Follow

Weekly Newsletter

Subscribe to our newsletter to get our newest articles instantly!

– Advertisement –

 

Popular News



edit
The Escapist

8 Mistakes That Will RUIN Your Weekend Trips Plan

Ruby Staff
Ruby Staff
August 30, 2021
10+ Pics That Prove Jennifer Is a Timeless Beauty
Medicaid Expansion Improves Hypertension and Diabetes Control
12 Summer Outfit Formulas for Lazy Girls Everywhere
Explained: How the President of US is Elected

Global Coronavirus Cases

Confirmed

0

Death

0


More Information:Covid-19 Statistics

More Popular from Daily News Circuit

Technology

“Revolutionary AI Apps Shake Up the Tech World as Bing Hits the Top Charts, Google and Mozilla Test Non-WebKit Browsers” – TechCrunch

By admin 30 Min Read

“Revolutionary AI Apps Shake Up the Tech World as Bing Hits the Top Charts, Google and Mozilla Test Non-WebKit Browsers” – TechCrunch

By admin
Health

“Invasion of Privacy? Uncovering the Risks of Contact Tracing Apps”

By admin 0 Min Read
- Advertisement -
Ad image
Technology

“Revolutionary AI Apps Shake Up the Tech World as Bing Hits the Top Charts, Google and Mozilla Test Non-WebKit Browsers” – TechCrunch

#apps #Bing #hits #Top #Charts #Google #Mozilla #test #nonWebKit #browsers #TechCrunch Welcome back to This Week…

By admin
Beautiful

The Unparalleled Splendor of the Outspoken Beauty Awards: Unveiling the Best Makeup Products of 2022!

#Outspoken #Beauty #Awards #Top #Makeup #Products The Outspoken Beauty Awards 2022 are here. Listen to today's…

By admin
Vacation

“Awe-Inspiring Quito: Unveiling the City’s 7 Reasons for Stealing Hearts & the Top 3 Places to Stay”

#reasons #Quito #steals #hearts #visitors #destinations #stay The city of Quito is the capital of Ecuador,…

By admin
Investment

“Harnessing the Power of Nature: A Tribute to Pitta – Achieving Sustainable Investing Through a Natural Capital Approach”

#Natural #Capital #Approach #Sustainable #Investing #Tribute #Pitta Goodbye, Pitta It was a sunny afternoon when I…

By admin
Technology

“Revolutionary AI Apps Shake Up the Tech World as Bing Hits the Top Charts, Google and Mozilla Test Non-WebKit Browsers” – TechCrunch

#apps #Bing #hits #Top #Charts #Google #Mozilla #test #nonWebKit #browsers #TechCrunch Welcome back to This Week…

By admin
Daily News Circuit

Stay in the loop and on the pulse of entertainment with Daily News Circuit – your ultimate source for sizzling news and electrifying videos from the heart of the entertainment world.

Categories

  • The Escapist
  • Entertainment
  • Bussiness

Quick Links

  • Advertise with us
  • Newsletters
  • Complaint
  • Deal

Copyright © 2023 Daily News Circuit | All Rights Reserved.

Removed from reading list

Undo
Welcome Back!

Sign in to your account

Lost your password?