/**
* Removes leading and trailing whitespace and collapses multiple
* consecutive whitespace characters into a single space.
*
* @param {string} str - The original string containing extra spaces.
* @returns {string} The normalized string.
*/
function removeExtraWhitespace(str) {
if (!str) return '';
// Step 1: trim() removes leading and trailing whitespace from the string.
// Step 2: replace(/\s+/g, ' ') matches any global sequence of 1 or more
// whitespace characters (spaces, tabs, newlines) and replaces it with a single space.
return str.trim().replace(/\s+/g, ' ');
}
// Input string containing arbitrary whitespace and padding
const s = " This is a test string with extra spaces. ";
// Clean the string using standard string methods
const cleanedString = removeExtraWhitespace(s);
console.log(cleanedString);
/*
run:
This is a test string with extra spaces.
*/