Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

171
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda