Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

288
Visualizações
.trim() for other characters?

Is there any function that can do .trim for specified characters or string?

Something like:

var x = '@@@hello world@@';
console.log(x.trim('@')); // prints 'hello world'

var y = 'hellohellohelloworld';
console.log(y.trim('hello')); // prints ' world'

var z = '@@hello@world@@';
console log(z.trim('@')); // prints 'hello@world'

Even tho I can do without this, it would be way less efficient and not as clean

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can use a pattern with an alternation | to match either what you want to remove at the start or at the end of the string by repeating it 1 or more time in a non capture group.

The repetition looks like this (?:@)+ for a single @ char, or like this (?:hello)+ for the word hello

If you want to make a function for it and want to pass any string, you have to escape the regex meta characters with a \

var x = '@@@hello world@@';
var y = 'hellohellohelloworld';
var z = '@@hello@world@@';
var a = '*+hello*+'

const customTrim = (strSource, strToRemove) => {
  let escaped = strToRemove.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
  return strSource.replace(new RegExp(`^(?:${escaped})+|(?:${escaped})+$`, 'g'), "")
};

console.log(customTrim(x, "\\s"));
console.log(customTrim(y, "hello"));
console.log(customTrim(z, "@"));
console.log(customTrim(a, "*+"));

about 4 years ago · Juan Pablo Isaza Relatório

0

export function trim(str: string, char: string): string {
  const leading = new RegExp(`^[${char}]+`);
  const trailing = new RegExp(`[${char}]+$`);
  return str.replace(leading, "").replace(trailing, "");
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda