header_logo
Post thumbnail
JAVASCRIPT

Understanding JavaScript Strings: Split, Trim, and Digit Sum Problem

By Arun Kumar

Mastering string manipulation in JavaScript is essential for writing clean, efficient code. But it can be pretty confusing for a beginner, and hence we understand why your search has led you here. And, you’re at the right place!

JavaScript offers various methods to manipulate strings and solve common programming problems. In this blog, we’ll understand JavaScript strings and explore how to calculate the sum of digits in a number and understand essential string manipulation methods like split() and trim(). Let’s begin!

Table of contents


  1. Sum of Digits Explanation with Steps
    • How to Solve the Sum of Digits:
  2. JavaScript String Manipulation Methods: Split and Trim
    • The split() Method
    • The trim() Method
  3. Differentiating Split and Trim
  4. Key Differences:
  5. Summary
  6. Conclusion

1. Sum of Digits Explanation with Steps

The “sum of digits” problem asks us to calculate the sum of all individual digits in a given number. 

For example, for the number 12345, 

we need to calculate 1+2+3+4+5, which equals 15.

How to Solve the Sum of Digits:

Method 1: Converting to String

function sumOfDigits(number) {
  // Step 1: Convert the number to a string
  const numStr = number.toString();
 
  // Step 2: Initialize a variable to hold our sum
  let sum = 0;
 
  // Step 3: Loop through each character (digit) in the string
  for (let i = 0; i < numStr.length; i++) {
    // Step 4: Convert each character back to a number and add to the sum
    sum += parseInt(numStr[i]);
  }
 
  // Step 5: Return the final sum
  return sum;
}

console.log(sumOfDigits(12345)); // Output: 15

Method 2: Mathematical Approach

function sumOfDigits(number) {
  // Step 1: Initialize sum
  let sum = 0;
 
  // Step 2: Loop until the number becomes 0
  while (number > 0) {
    // Step 3: Get the last digit using modulo
    sum += number % 10;
   
    // Step 4: Remove the last digit
    number = Math.floor(number / 10);
  }
 
  // Step 5: Return the sum
  return sum;
}

console.log(sumOfDigits(12345)); // Output: 15

Method 3: Using Array Methods

function sumOfDigits(number) {
  // Step 1: Convert to string, split into array, reduce to sum
  Return number.toString()
    .split(”)
    .reduce((sum, digit) => sum + parseInt(digit), 0);
}

console.log(sumOfDigits(12345)); // Output: 15

2. JavaScript String Manipulation Methods: Split and Trim

The split() Method

The split() method in JavaScript divides a string into an array of substrings based on a specified separator.

Syntax:

string.split(separator, limit)

Parameters:

  • separator: The character or pattern used to determine where to make each split
  • limit (optional): An integer that limits the number of splits

Examples:

// Split by space
const numbers = “2 3 4 5 6 7 8”;
console.log(numbers.split(” “)); // [“2”, “3”, “4”, “5”, “6”, “7”, “8”]

// Split by comma
const fruits = “apple,banana,orange”;
console.log(fruits.split(“,”)); // [“apple”, “banana”, “orange”]

// Split into individual characters
const word = “hello”;
console.log(word.split(“”)); // [“h”, “e”, “l”, “l”, “o”]

// Using a limit
const data = “one,two,three,four,five”;
console.log(data.split(“,”, 3)); // [“one”, “two”, “three”]

The trim() Method

The trim() method removes whitespace from both ends of a string, not from the middle.

Syntax:

string.trim()

Examples:

// Remove spaces from both ends
const text = ”   Hello World!   “;
console.log(text.trim()); // “Hello World!”

// Only trims from the beginning and end
const spaced = ”  Hello   World!  “;
console.log(spaced.trim()); // “Hello   World!”

// Additional trim methods
console.log(”  Hello”.trimStart()); // “Hello”
console.log(“Hello  “.trimEnd());   // “Hello”
MDN

3. Differentiating Split and Trim

Featuresplit()trim()
PurposeDivides a string into an array of substringsRemoves whitespace from the beginning and end of a string
Return TypeArrayString
ParametersSeparator, optional limitNone
Changes OriginalNo (returns new array)No (returns new string)
Use CaseParsing data, tokenizing textCleaning user input
Handles WhitespaceCan split on whitespaceOnly removes whitespace from the ends

Key Differences:

  1. split() transforms a string into an array while trim() keeps it as a string
  2. split() can divide a string at any specified character or pattern, while trim() only removes whitespace characters
  3. Split() can create multiple substrings, while trim() modifies the original string by removing leading/trailing spaces

4. Summary

  • The sum of Digits can be calculated using:
    • String conversion and iteration
    • Mathematical operations (modulo and division)
    • Array methods with split() and reduce()
  • split() is used for:
    • Converting space-separated values into arrays
    • Breaking down strings into individual characters
    • Parsing CSV or other delimited data formats
  • trim() is used for:
    • Removing unnecessary whitespace from user input
    • Normalizing strings before comparison or validation
    • Cleaning data from external sources

Both methods are non-destructive, meaning they don’t modify the original string but return a new value.

If you’re looking to master JavaScript from scratch, the JavaScript Course in 100 days, by GUVI, is a perfect fit. It offers a structured, hands-on approach with daily challenges, making complex concepts like strings, arrays, and functions easy to grasp, even for beginners.

MDN

5. Conclusion

Understanding string manipulation methods like split() and trim() is fundamental for effective JavaScript programming. These methods provide elegant solutions for common tasks like parsing input data, cleaning strings, and transforming data formats.

The sum of digits problem demonstrates how these string methods can be combined with other programming techniques to solve algorithmic challenges. By converting a number to a string and utilizing split(), we can transform our data into a format that’s easier to process.

As you develop your JavaScript skills, mastering these string manipulation methods will help you write cleaner, more efficient code and solve a wide range of programming problems with greater ease.

When processing user input, remember to use trim() to remove unwanted whitespace. When you need to work with parts of a string individually, split() will be your go-to method. Together, these tools form an essential part of a JavaScript developer’s toolkit.

Success Stories

Did you enjoy this article?

Schedule 1:1 free counselling

Similar Articles

Loading...
Share logo Copy link
Power Packed Webinars
Free Webinar Icon
Power Packed Webinars
Subscribe now for FREE! 🔔
close
Webinar ad
Table of contents Table of contents
Table of contents Articles
Close button

  1. Sum of Digits Explanation with Steps
    • How to Solve the Sum of Digits:
  2. JavaScript String Manipulation Methods: Split and Trim
    • The split() Method
    • The trim() Method
  3. Differentiating Split and Trim
  4. Key Differences:
  5. Summary
  6. Conclusion