martes, 9 de agosto de 2022

Manejar Espacios en blanco

 Eliminar espacios en blanco:

 https://stackoverflow.com/questions/10800355/remove-whitespaces-inside-a-string-in-javascript


function removeWhitespaces(string, i = 0, res = "") {
  if (i >= string.length)
    return res
  else
  if (string[i] == " ")
    return removeWhitespaces(string, i + 1, res)
  else
    return removeWhitespaces(string, i + 1, res += string[i])
}

console.log(removeWhitespaces(" Hello World,   how is it going ? "))
resp: HelloWorld,howisitgoing?


Verificar si existe espacios en blanco:

function hasMoreThanOneWhitespace(
  string: string,
  i = 0,
  res = '',
  result = false
): boolean {
  if (i >= string.length || result) {
    return result;
  } else {
    if (string[i] == ' ') {
      if (string[i + 1] == ' ')
        return hasMoreThanOneWhitespace(string, i + 1, res, true);
      else
        return hasMoreThanOneWhitespace(
          string,
          i + 1,
          (res += string[i]),
          false
        );
    } else {
      return hasMoreThanOneWhitespace(string, i + 1, (res += string[i]), false);
    }
  }
}


  static oneSpacePerWord(): ValidatorFn {
    return (control: AbstractControl): { [key: string]: any } | null => {
      if (!isEmptyInputValue(control.value) && control.value.length > 1) {
        const value = control.value as string;
        if (hasMoreThanOneWhitespace(value)) {
          return {
            predicate: 'No debe contener más de un espacio por palabra.',
          };
        }
        return null;
      }
      return null;
    };
  }