0

I need to create sanitized URLs slugs from title field written by users. The input will be something like:

const title = 'Puede àgregar unÁ imagen en miniatura (JPG, PNG, GIF) a tu_publicación-que *hola* #@\÷@¡'¿¸˛¸ aparecerá en todas las listas del foro. Debe ser una URL de imagen válida, nosotros nos encargamos de cambiarle el tamaño.'

And i need to generate a string that is sanitized like this:

'puede_agregar_una_imagen_en_miniatura_jpg_png_gif_a_tu_publicacion_que_hola_aparecera_en_todas_las_listas_del_foro_debe_ser_una_URL_de_imagen_valida_nosotros_nos_encargamos_de_cambiarle_el_tamano'

I tried to use replace() method but once I get into the regex part i cannot figure out how to match more than spaces.

title.replace(/[\s-,*()#$%]/g, '_').toLocaleLowerCase()

I want to be able to replace:

  • All symbols (*,) to nothing.
  • All - to _
  • All spaces to underlines '_'
  • All áóúíéèàòù, etc. to normalized lettters.
  • other characters like ñ should be replaced to n
skara9
  • 4,042
  • 1
  • 6
  • 21
Minide
  • 165
  • 1
  • 2
  • 16
  • 1
    Does this answer your question? [Encode URL in JavaScript?](https://stackoverflow.com/questions/332872/encode-url-in-javascript) – possum Jan 23 '22 at 13:25
  • Have you evaluated if [encodeURIComponent](https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent) fits your needs? Altthough not replacing characters as you want, it still makes sure strings are URL safe which I understand as the primary goal. – alexanderdavide Jan 23 '22 at 13:26
  • to do what you want `title.replace(/(\s|-)/g, '_').normalize('NFKD').replace(/\W/g, '').toLowerCase()` – skara9 Jan 23 '22 at 13:40

0 Answers0