xxxxxxxxxx
const str = " This is a test ";
const trimmedStr = str.replace(/\s+/g, " ").trim();
console.log(trimmedStr);
xxxxxxxxxx
const sentence = ' My string with a lot of Whitespace. '.replace(/\s+/g, ' ').trim()
// 'My string with a lot of Whitespace.'
xxxxxxxxxx
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!
xxxxxxxxxx
const str = " Hello World ";
const trimmedStr = str.replace(/\s+/g, ' ').trim();
console.log(trimmedStr);
xxxxxxxxxx
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;
}