Which regular expression can I use to remove double spaces in Javascript or PHP?

Asked

Viewed 15,565 times

10

What regular expression can I use to remove excess white space? I mean, leave them with the amount of normalized spaces.

Example

Of:

$string = 'Estou no    Stack   Overflow em Português   ';

To:

$string = 'Estou no Stack Overflow em Português';

I would like examples in PHP and Javascript.

3 answers

18


If you consider breaking lines, tabs, among others as spaces use \s, otherwise you can use ( ) - as in the example.

PHP

$str = preg_replace('/( )+/', ' ', "stack    overflow");    

Javascript

var str = "stack    overflow".replace(/( )+/g, ' ');

About the regex:

( ) captures empty spaces. The + indicates that it will take all subsequent (empty) sentences.

9

Some types of "writeSpace"

" " espaço simples - represente o " " espaço
\n - representa a quebra de linha
\r - representa o retorno de carro
\t - representa um tab
\v - representa um tab vertical (nunca vi, nem usei)
\f - representa o avanço de pagina
\s - engloba todos os demais

Some REGEX

/ {2,}/      - captura apenas dois ou mais espaços
/\n{2,}/     - captura apenas linhas duplas
/(\r\n){2,}/ - captura apenas linhas duplas, que possuam retorno de carro (alguns editores poem por padrão `\r\n` ao pressionar enter)

Your situation

PHP

$str = preg_replace('/( ){2,}/', '$1', $str);

Javascript

str = str.replace(/( ){2,}/g, '$1');

Explanation

( )  - captura um espaço simples e gera um grupo
{2,} - quantifica um no minimo dois ao infinito
$1   - recupera o grupo
  • Just pointing out this REGEX always replace several spaces by a space, if you want to leave no space at the beginning or at the end, both PHP and Javascript have the function trim. or if you want I can do REGEX also that it is more complicated and not recommenced, since the function exste.

2

That way it already resolves:

Javascript:

var text = 'Estou no    Stack   Overflow em Português   ';
    text = text.replace(/\s+/g, " ");

PHP:

$text = 'Estou no    Stack   Overflow em Português   ';
$text = preg_replace('/\s+/', " ",$text);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.