Regex para reemplazar varios espacios con un solo espacio


Dada una cadena como:

"The dog      has a long   tail, and it     is RED!"

¿Qué tipo de magia de jQuery o JavaScript se puede usar para mantener los espacios a un solo espacio máximo?

Objetivo:

"The dog has a long tail, and it is RED!"
Author: TylerH, 2009-12-30

18 answers

Dado que también desea cubrir pestañas, nuevas líneas, etc., simplemente reemplace \s\s+ con ' ':

string = string.replace(/\s\s+/g, ' ');

Si realmente desea cubrir solo espacios (y por lo tanto no pestañas, nuevas líneas, etc.), hágalo:

string = string.replace(/  +/g, ' ');
 636
Author: BalusC,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-18 07:52:15

Ya que usted parece estar interesado en el rendimiento, he perfilado estos con firebug. Estos son los resultados que obtuve:

str.replace( / +/g, ' ' )        ->  790ms
str.replace( /  +/g, ' ' )       ->  380ms
str.replace( / {2,}/g, ' ' )     ->  470ms
str.replace( /\s\s+/g, ' ' )     ->  390ms
str.replace( / +(?= )/g, ' ')    -> 3250ms

Esto es en Firefox, ejecutando reemplazos de cadenas de 100k.

Te animo a hacer tus propias pruebas de perfil con firebug, si crees que el rendimiento es un problema. Los humanos son notoriamente malos para predecir dónde se encuentran los cuellos de botella en sus programas.

(Además, tenga en cuenta que la barra de herramientas del desarrollador de IE 8 también tiene un generador de perfiles incorporado -- cómo es el rendimiento en IE.)

 128
Author: Edward Loper,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-12-30 19:26:37
var str = "The      dog        has a long tail,      and it is RED!";
str = str.replace(/ {2,}/g,' ');

EDITAR: Si desea reemplazar todo tipo de caracteres de espacio en blanco, la forma más eficiente sería así:

str = str.replace(/\s{2,}/g,' ');
 37
Author: watain,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-12-30 17:39:13

Esta es una solución, aunque tendrá como objetivo todos los caracteres de espacio:

"The      dog        has a long tail,      and it is RED!".replace(/\s\s+/g, ' ')

"The dog has a long tail, and it is RED!"

Editar : Esto es probablemente mejor ya que apunta a un espacio seguido de 1 o más espacios:

"The      dog        has a long tail,      and it is RED!".replace(/  +/g, ' ')

"The dog has a long tail, and it is RED!"

Método alternativo:

"The      dog        has a long tail,      and it is RED!".replace(/ {2,}/g, ' ')
"The dog has a long tail, and it is RED!"

No utilicé /\s+/ por sí mismo, ya que reemplaza espacios que abarcan 1 carácter varias veces y podría ser menos eficiente, ya que se dirige a más de lo necesario.

No probé profundamente ninguno de estos, así que lmk si hay error.

También, si vas a hacer reemplazo de cadena recuerda reasignar la variable / propiedad a su propio reemplazo, por ejemplo:

var string = 'foo'
string = string.replace('foo', '')

Usando jQuery.prototipo.texto:

var el = $('span:eq(0)');
el.text( el.text().replace(/\d+/, '') )
 15
Author: meder omuraliev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-12-30 17:45:18

Tengo este método, lo llamo el método Derp por falta de un nombre mejor.

while (str.indexOf("  ") !== -1) {
    str = str.replace(/  /g, " ");
}

Ejecutarlo en JSPerf da algunos resultados sorprendentes.

 13
Author: Nenotlep,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-04-26 10:36:36

Más robusto:

function trim(word)
{
    word = word.replace(/[^\x21-\x7E]+/g, ' '); // change non-printing chars to spaces
    return word.replace(/^\s+|\s+$/g, '');      // remove leading/trailing spaces
}
 9
Author: Chris,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-18 12:18:24

Un método más robusto: Esto se encarga de también eliminar los espacios inicial y final, si existen. Eg:

// NOTE the possible initial and trailing spaces
var str = "  The dog      has a long   tail, and it     is RED!  "

str = str.replace(/^\s+|\s+$|\s+(?=\s)/g, "");

// str -> "The dog has a long tail, and it is RED !"

Su ejemplo no tenía esos espacios, pero también son un escenario muy común, y la respuesta aceptada fue solo recortarlos en espacios individuales, como: "The ... ROJO! ", que no es lo que normalmente necesitarás.

 9
Author: Ethan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-12 05:00:38

Sugiero

string = string.replace(/ +/g," ");

Para solo espacios
O

string = string.replace(/(\s)+/g,"$1");

Para convertir múltiples retornos en un solo retorno también.

 8
Author: Leonard Meagher,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-05-14 00:59:46

Aquí hay una solución alternativa si no desea usar reemplazar (reemplazar espacios en una cadena sin usar reemplazar javascript)

var str="The dog      has a long   tail, and it     is RED!";
var rule=/\s{1,}/g;
str = str.split(rule).join(" "); 
document.write(str);
 6
Author: imos,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-18 12:18:13

Sé que llego tarde a la fiesta, pero descubrí una buena solución.

Aquí está:

var myStr = myStr.replace(/[ ][ ]*/g, ' ');
 5
Author: ToXic73,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-22 06:16:23

Respuesta completa sin cifrar para novatos et al.

Esto es para todos los tontos como yo que prueban los guiones escritos por algunos de ustedes que no funcionan.

Los siguientes 3 ejemplos son los pasos que tomé para eliminar caracteres especiales y espacios adicionales en los siguientes 3 sitios web (todos los cuales funcionan perfectamente) {1. EtaVisa.com 2. EtaStatus.com 3. Tikun.com así que sé que estos funcionan perfectamente.

Hemos encadenado estos junto con más de 50 en un tiempo y sin problemas.

/ / Esto elimina los caracteres especiales + 0-9 y permite solo letras (mayúsculas y minúsculas)

function NoDoublesPls1()
{
var str=document.getElementById("NoDoubles1");
var regex=/[^a-z]/gi;
str.value=str.value.replace(regex ,"");
}

/ / Esto elimina los caracteres especiales y permite solo letras (mayúsculas y minúsculas) y 0-9 y espacios

function NoDoublesPls2()
{
var str=document.getElementById("NoDoubles2");
var regex=/[^a-z 0-9]/gi;
str.value=str.value.replace(regex ,"");
}

/ / Esto elimina los caracteres especiales y permite solo letras (mayúsculas y minúsculas) y 0-9 y espacios // El .reemplazar(/\s\s+/g,"") al final elimina espacios excesivos // cuando usé comillas simples, no lo hizo trabajo.

function NoDoublesPls3()
{    var str=document.getElementById("NoDoubles3");
var regex=/[^a-z 0-9]/gi;
str.value=str.value.replace(regex ,"") .replace(/\s\s+/g, " ");
}

::SIGUIENTE:: Guardar #3 como a .js // Llamé a mis NoDoubles.js

::SIGUIENTE:: Incluya su JS en su página

 <script language="JavaScript" src="js/NoDoubles.js"></script>

Incluya esto en el campo de su formulario:: como

<INPUT type="text" name="Name"
     onKeyUp="NoDoublesPls3()" onKeyDown="NoDoublesPls3()" id="NoDoubles3"/>

Para que se vea así

<INPUT type="text" name="Name" onKeyUp="NoDoublesPls3()" onKeyDown="NoDoublesPls3()" id="NoDoubles3"/>

Esto eliminará caracteres especiales, permitirá espacios individuales y eliminará espacios adicionales.

 5
Author: PatFoster,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-24 08:24:59

También una posibilidad:

str.replace( /\s+/g, ' ' )
 4
Author: rfunduk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-12-30 17:32:52

Jquery tiene la función trim() que básicamente convierte algo como esto "FOo Bar" en "FOo Bar".

var string = "  My     String with  Multiple lines    ";
string.trim(); // output "My String with Multiple lines"

Es mucho más útil porque elimina automáticamente los espacios vacíos al principio y al final de la cadena también. No se necesita regex.

 2
Author: Eryk Wróbel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-17 07:30:02
var myregexp = new RegExp(/ {2,}/g);

str = str.replace(myregexp,' ');
 0
Author: marvin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-12-30 17:37:16
var string = "The dog      has a long   tail, and it     is RED!";
var replaced = string.replace(/ +/g, " ");

O si también desea reemplazar las pestañas:

var replaced = string.replace(/\s+/g, " ");
 0
Author: Brian Campbell,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-12-30 17:38:33

Podemos usar la siguiente expresión regular explicada con la ayuda del comando sed system. La expresión regular similar se puede utilizar en otros idiomas y plataformas.

Añadir el texto en algún archivo decir test

manjeet-laptop:Desktop manjeet$ cat test
"The dog      has a long   tail, and it     is RED!"

Podemos usar la siguiente expresión regular para reemplazar todos los espacios en blanco con un solo espacio

manjeet-laptop:Desktop manjeet$ sed 's/ \{1,\}/ /g' test
"The dog has a long tail, and it is RED!"

Espero que esto sirva para el propósito

 0
Author: minhas23,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-19 09:35:17

Intente esto para reemplazar varios espacios con un solo espacio.

<script type="text/javascript">
    var myStr = "The dog      has a long   tail, and it     is RED!";
    alert(myStr);  // Output 'The dog      has a long   tail, and it     is RED!'

    var newStr = myStr.replace(/  +/g, ' ');
    alert(newStr);  // Output 'The dog has a long tail, and it is RED!'
</script>

Read more @ Sustitución de Múltiples Espacios por un Solo Espacio

 0
Author: jonathan klevin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-01 11:53:30
var text = `xxx  df dfvdfv  df    
                     dfv`.split(/[\s,\t,\r,\n]+/).filter(x=>x).join(' ');

Resultado:

"xxx df dfvdfv df dfv"
 -1
Author: Toolkit,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-05 15:22:12