Eliminar espacios de un texto o una cadena con JS

Spread the love

En JavaScript hay muchas formas para eliminar los espacios de una cadena de texto, dependiendo de su necesidad podrá usar un método u otro.

Tabla de Contenido:

  1. replace() para reemplazar los espacios en blanco.
  2. trim() para eliminar los espacios a los extremos.
  3. split() y join() para reemplazar los espacios en blanco.

Video Tutorial:

Usando replace():

Este método devuelve una nueva cadena con algunas o todas las coincidencias reemplazadas; podemos utilizarlo para buscar los espacios de una cadena y reemplazarlo por un valor diferente.

replace() se llama directamente desde la cadena, y requiere dos valores para funcionar PATRON y REEMPLAZO.


String.replace(PATRON, REEMPLAZO)

PATRON puede ser una cadena o un objeto RegExp, que será reemplazado por REEMPLAZO.

REEMPLAZO puede ser una cadena o una función que será llamada para cada coincidencia y colocarla en lugar de PATRON.

Ejemplo 1:

string.replace(/ /g, «»); esta expresión regular contiene un espacio en blanco (» «), y la propiedad global.

Esto buscara todos los espacios en blanco de una cadena y los reemplazara por una cadena vacía.

var cadena = 'remover los espacios vacios de una cadena';

var cadena2 = cadena.replace(/ /g, "");


Ejemplo 2:

string.replace(/\s+/g, »); esta expresión regular ‘\s’, hace referencia a cualquier símbolo de espacio en blanco: espacios, tabulaciones o saltos de líneas.

var cadena = `
los espacios vacios 
de una cadena`;

var cadena2 = cadena.replace(/\s+/g, '');


Usando trim():

Este método elimina los espacios en blanco o vacíos en ambos extremos de una cadena.

Los espacios en blanco en este contexto, hace referencia a todos los caracteres sin contenido como: espacios, tabulaciones, etc.

trim() se llama directamente desde la cadena, y no requiere ningún parámetro adicional para funcionar.




var cadena = '    remover extremos de una cadena    ';

var cadena = cadena.trim();

//remover extremos de una cadena

Usando split() y join() juntos:

El método split() divide una cadena en array, y devuelve un nuevo array. *requiere un carácter como delimitador.

El método join() concadena un array, y devuelve una nueva cadena.

Usamos split para dividir una cadena en un array con un carácter de espacio vacío » » como delimitador, después con join() convertimos el array en una cadena.


var cadena = 'remover los espacios vacios de una cadena';

var cadena2 = cadena.split(" ").join("");


10 respuestas a “Eliminar espacios de un texto o una cadena con JS”

  1. After research just a few of the weblog posts in your website now, and I truly like your way of blogging. I bookmarked it to my bookmark website list and shall be checking back soon. Pls check out my website as effectively and let me know what you think.

  2. Youre so cool! I dont suppose Ive read something like this before. So good to seek out any individual with some original ideas on this subject. realy thanks for beginning this up. this website is something that is needed on the net, somebody with a little bit originality. helpful job for bringing something new to the internet!

  3. Oh my goodness! a tremendous article dude. Thank you However I am experiencing challenge with ur rss . Don抰 know why Unable to subscribe to it. Is there anybody getting identical rss problem? Anyone who knows kindly respond. Thnkx

  4. There are some fascinating deadlines on this article however I don抰 know if I see all of them middle to heart. There may be some validity but I will take hold opinion till I look into it further. Good article , thanks and we want more! Added to FeedBurner as nicely

  5. I truly wanted to compose a brief word in order to appreciate you for all the wonderful hints you are showing here. My incredibly long internet research has at the end been honored with high-quality knowledge to share with my co-workers. I would claim that many of us readers actually are very fortunate to exist in a fine site with very many outstanding professionals with useful plans. I feel extremely lucky to have discovered your weblog and look forward to plenty of more fun times reading here. Thanks a lot once more for all the details.

  6. I in addition to my friends appeared to be analyzing the great items located on the blog and then all of the sudden came up with an awful suspicion I never expressed respect to the website owner for them. The guys came as a consequence stimulated to read them and now have very much been loving them. I appreciate you for genuinely so helpful and also for pick out such brilliant guides most people are really eager to understand about. Our own sincere apologies for not expressing gratitude to you earlier.

  7. Thanks so much for providing individuals with an extremely nice possiblity to read critical reviews from this website. It really is so lovely and stuffed with a lot of fun for me personally and my office mates to visit your website nearly thrice every week to read through the newest guidance you will have. And indeed, I’m just certainly pleased for the awesome points you give. Selected 1 areas in this article are completely the most efficient we have all ever had.

  8. I am only commenting to let you know of the perfect experience my friend’s princess found visiting the blog. She noticed some details, not to mention how it is like to have a great giving mindset to have many people completely completely grasp specific advanced topics. You truly did more than her expected results. Thanks for delivering such precious, dependable, explanatory and even unique tips on the topic to Kate.

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *