Algorithm


  1. Input: Take a string as input.
  2. Initialize: Create variables to store the start and end indices of the trimmed string.
    • Set startIndex to 0.
    • Set endIndex to the length of the string minus 1.
  3. Trimming from the start:
    • Iterate from the beginning of the string until a non-whitespace character is found.
    • Update startIndex to the index of the first non-whitespace character.
  4. Trimming from the end:
    • Iterate from the end of the string until a non-whitespace character is found.
    • Update endIndex to the index of the last non-whitespace character.
  5. Extract the trimmed string:
    • Use the substring method or array slicing to extract the substring from startIndex to endIndex.
  6. Output: Return the trimmed string.

 

Code Examples

#1 Code Example- JavaScript Programing Trim a String

Code - Javascript Programming

// program to trim a string

const string = '      Hello World       ';

const result = string.trim();

console.log(result);
Copy The Code & Try With Live Editor

Output

x
+
cmd
Hello World

#2 Code Example- Trim a String Using RegEx

Code - Javascript Programming

// program to trim a string

function trimString(x) {
    let trimValue = x.replace(/^\s+|\s+$/g,'');
    return trimValue;
}

const result = trimString('    Hello world    ');
console.log(result);
Copy The Code & Try With Live Editor

Output

x
+
cmd
Hello World
Advertisements

Demonstration


JavaScript Programing Example to Trim a String-DevsEnv

Previous
JavaScript Practice Example #3 - Assign 3 Variables and Print Good Way