const trimString = value => { const allStringElementsToArray = value.split(''); // transform "abcd efgh" to ['a', 'b', 'c', 'd',' ','e', 'f','g','h'] const allElementsSanitized = allStringElementsToArray.map(e => e.trim()); // Remove all blank spaces from array const finalValue = allElementsSanitized.join(''); // Transform the sanitized array ['a','b','c','d','e','f','g','h'] to 'abcdefgh' return finalValue; }newString = string.replace(/\s+/g,' ').trim();const sentence = ' My string with a lot of Whitespace. '.replace(/\s+/g, ' ').trim() // 'My string with a lot of Whitespace.' var str = " Some text "; str.trim(); // str = "Some text"const str = " This is a test "; const trimmedStr = str.replace(/\s+/g, " ").trim(); console.log(trimmedStr);const removeExtraSpaces = (string) => { const newText = string .replace(/\s+/g, " ") .replace(/^\s+|\s+$/g, "") .replace(/ +(\W)/g, "$1"); return newText }; console.log(removeExtraSpaces(" Hello World!")) //Hello World!const str = " Hello World "; const trimmedStr = str.replace(/\s+/g, ' ').trim(); console.log(trimmedStr);