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

172
Visualizações
Replace spaces with one dash and only allow Aphanumeric in Javascript

I'm trying to achieve this kind of result:

From This is a test to this-is-a-test

But I'd like to implement these rules:

  • Convert all spaces to dash.
  • Only allow one space (dash) between each two words.
  • Don't allow a dash a the beginning or end of the sentence.
  • Only allow letters, numbers and à ç _ è - é ù.

For now I'm using this partial solution:

const str = "This is dope";
const result = str.trim().replace(/\s+/g, "-").toLowerCase();
console.log(result) // this-is-dope

But this doesn't solve the whole problem because it doesn't have all the rules I mentioned.

I appreciate any help in this matter!

EDIT: I'm using React, and I need to implement this solution in an input field as follow :

Using the solution from mplungjan :

// state to hold the typed value
const [text, setText] = useState("");

<input
  type="text"
  onChange={(e) => {
    setText(
      e.target.value
        .trim()
        .replace(/^-+|-+$/g, "")
        .replace(/[-\s]+/g, "-")
        .replace(/[^a-zA-Z0-9\-àç_èéù]/g, "")
        .toLowerCase()
    );
    // unable to type spaces or dashes at all so far
    console.log(text);
  }}
  value={text}
/>
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can use

function App() {
  const [text, setText] = React.useState('');
  function toKebabCase({ target: { value } }) {
    setText( value.replace(/[-\s]+/g, "-").replace(/^-/, '').replace(/[^a-zA-Z0-9àç_èéù-]+/g, "").toLowerCase() )
  }
  return  <div>
      Text: <input type='text' onChange={toKebabCase} value={text} />
  </div>
}
ReactDOM.render(<App/>, document.querySelector('#root'))
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></div>

The value.replace(/[-\s]+/g, "-").replace(/^-/, '').replace(/[^a-zA-Z0-9àç_èéù-]+/g, "").toLowerCase() will

  • replace one or more whitespace and/or hyphen chars with a single - (with .replace(/[-\s]+/g, "-")) and then
  • remove the first - (with .replace(/^-/, ''))
  • remove any chars other than ASCII letters, digits, _, -, à, ç, è, é and ù (with .replace(/[^a-zA-Z0-9àç_èéù-]+/g, ""))
  • turn the result into lower case (with .toLowerCase()).
about 4 years ago · Juan Pablo Isaza Relatório

0

const str = "- This is0 dope $$ !";
const result = str.toLowerCase().replace(/[^0-9a-z ]+/g,'').trim().replace(/\s+/g, '-');
console.log(result)

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