Search This Blog

2026/09/22

Javascript:TrimLeft & TrimRight

function trimLeft(str) {
  if (typeof str !== 'string') {
    throw new TypeError('Expected a string');
  }
  return str.replace(/^\s+/, '');
}
function trimRight(str) {
  if (typeof str !== 'string') {
    throw new TypeError('Expected a string');
  }
return str.replace(/\s+$/, '');
}

let input = '   Hello, World!   ';
let trimmedLeft = trimLeft(input);
console.log("'" + trimmedLeft + "'"); // Output: 'Hello, World!   '

let trimmedRight = trimRight(input);
console.log("'" + trimmedRight + "'"); // Output: '   Hello, World!'