Okay, here's a short JavaScript function using the built-in trim() method, which is specifically designed for this purpose. It removes spaces, tabs, new lines (\n, \r), and other whitespace characters from both ends of the string.
javascript
/**
* Trims whitespace characters (spaces, new lines, tabs, etc.) from both
* the beginning and end of a string.
*
* @param {string} inputString The string to trim.
* @returns {string} The trimmed string. Returns an empty string if input is not a string.
*/
function trimWhitespace(inputString) {
// The built-in trim() method handles spaces, new lines (\n, \r), tabs (\t),
// form feeds (\f), and vertical tabs (\v) from both ends.
if (typeof inputString !== 'string') {
// Handle non-string input gracefully, e.g., return an empty string
return '';
}
return inputString.trim();
}
// --- Example Usage ---
let myString = " \n Hello World! \t\r\n ";
let trimmedString = trimWhitespace(myString);
console.log("Original:");
console.log(`'${myString}'`); // Using backticks to show whitespace
console.log("Trimmed:");
console.log(`'${trimmedString}'`); // Using backticks to show whitespace
let anotherString = "No trimming needed.";
console.log(`'${trimWhitespace(anotherString)}'`);
let stringWithInternalWhitespace = " Hello World ";
console.log(`'${trimWhitespace(stringWithInternalWhitespace)}'`); // Note: Internal whitespace is preserved
let nonStringInput = null;
console.log(`'${trimWhitespace(nonStringInput)}'`); // Handles non-string input
Explanation:
function trimWhitespace(inputString): Defines a function named trimWhitespace that takes one argument, inputString.
if (typeof inputString !== 'string') { return ''; }: This is a basic check to ensure the input is actually a string before attempting to call string methods on it. If not, it returns an empty string to avoid errors.
return inputString.trim();: This is the core line. The trim() method is a standard JavaScript String method that returns a new string with leading and trailing whitespace removed. It does not modify the original string.