JavaScript: Strip leading and trailing spaces from a string
JavaScript String: Exercise-23 with Solution
Write a JavaScript function to strip leading and trailing spaces from a string.
Test Data:
console.log(strip('w3resource '));
console.log(strip(' w3resource'));
console.log(strip(' w3resource '));
Output :
"w3resource"
"w3resource"
"w3resource"
Sample Solution:
JavaScript Code:
// Define a function named strip that removes leading and trailing whitespaces from a string
function strip(str) {
// Use the replace method with a regular expression to remove leading and trailing whitespaces
return str.replace(/^\s+|\s+$/g, '');
}
// Test the strip function with various input strings and log the results
console.log(strip('w3resource ')); // Output: 'w3resource'
console.log(strip(' w3resource')); // Output: 'w3resource'
console.log(strip(' w3resource ')); // Output: 'w3resource'
Output:
w3resource w3resource w3resource.
Explanation:
In the exercise above,
- function strip(str) {: This line declares a function named "strip()" that takes a string 'str' as input.
- return str.replace(/^\s+|\s+$/g, '');: This line uses the "replace()" method with a regular expression to remove leading and trailing whitespaces (\s represents whitespace characters). The regular expression ^\s+ matches one or more whitespace characters at the beginning of the string, and \s+$ matches one or more whitespace characters at the end of the string. The 'g' flag ensures that all occurrences of leading and trailing whitespaces are replaced with an empty string, effectively removing them.
- }: This line closes the function definition.
- The subsequent console.log statements test the "strip()" function with different input strings and output the results.
Flowchart:
Live Demo:
See the Pen JavaScript Strip leading and trailing spaces from a string - string-ex-23 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus.
Previous: Write a JavaScript function to get a part of string after a specified character.
Next: Write a JavaScript function to truncate a string to a certain number of words.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/javascript-exercises/javascript-string-exercise-23.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics