JavaScript: Alternet of trim function using regular expression
JavaScript validation with regular expression: Exercise-5 with Solution
Regex Trim Function
Write a JavaScript program that works as a regular expression trim function (string).
Visual Presentation:

Sample Solution:
JavaScript Code:
function Trim(str)
{
var result;
if (typeof str === 'string')
{
result = str.replace(/^\s+|\s+$/g, '');
return result;
}
else
{
return false;
}
}
console.log(Trim(' w3resource '));
Output:
w3resource
Flowchart:

Live Demo:
See the Pen javascript-regexp-exercise-5 by w3resource (@w3resource) on CodePen.
For more Practice: Solve these Related Problems:
- Write a JavaScript function that removes leading and trailing whitespace from a string using a regular expression.
- Write a JavaScript function that implements a custom trim() method using regex replace and tests it on various strings.
- Write a JavaScript function that trims not only spaces but also tab characters and newlines from both ends of a string.
- Write a JavaScript function that mimics the behavior of String.prototype.trim() without using any built-in trim methods.
Improve this sample solution and post your code through Disqus.
Previous: Write a JavaScript program to search a date within a string.
Next: Write a JavaScript program to count number of words in string.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics