Algorithm
- Input: Take a string as input.
- 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.
- Set
- 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.
- 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.
- Extract the trimmed string:
- Use the
substring
method or array slicing to extract the substring fromstartIndex
toendIndex
.
- Use the
- 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
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
Hello World
Demonstration
JavaScript Programing Example to Trim a String-DevsEnv