Remove spaces from a string from the second occurrence

6

I'm currently removing spaces using a simple replace() and adding a space that I must preserve between the third and fourth character using substr()

let str = 'abc defghijk lmnop qrstuv wx y z'

str = str.replace(/\s+/g, '')
// resultado: 'abcdefghijklmnopqrstuvwxyz'

str = str.substr(0, 3) + ' ' + str.substr(3, str.length)

console.log(str)

What is the most succinct way to get the same result using only the replace() method?

PS: I really have little knowledge about using RegExp

    
asked by anonymous 27.07.2018 / 16:34

3 answers

7

Using only replace can also be done, although it probably does not pay for performance / readability / support.

You can use the following regex:

(?<=\s.*)\s+

Explanation:

(?<=   - Positive lookbehind, que tenha algo atrás
\s+.*) - Que tenha espaço seguido de qualquer coisa
\s+    - O espaço a ser capturado

View this regex on regex101

Then you can read this regex as capturing a space that has another space behind followed by anything. For this reason you will not get the first one because it has no space behind.

It's worth noting that this uses positive lookbehind , which was added to the javascript shortly so it probably will not work on older browsers. The second note is that this is a variable-sized lookbehind that most regex engines do not even support.

Example:

let str = 'abc defghijk lmnop qrstuv wx y z'

str = str.replace(/(?<=\s+.*)\s+/g, '')

console.log(str)

So I think the best solution is to make it simple and use a indexOf as suggested to get the first space and replace it from there.

    
27.07.2018 / 17:39
5

You can capture the position of the first space with indexOf() , reserve this prefix, and narrow the scope of your replace() , but the solution is not through the regex.

let str = 'abc defghijk lmnop qrstuv wx y z';
let prefix = str.substr(0,str.indexOf(' ')+1);

str = prefix + str.substr(prefix.length).replace(/\s+/g, '');

console.log(str);
//abc defghijklmnopqrstuvwxyz
    
27.07.2018 / 17:26
0

Split + Join

An alternative to keep the first space is to use Split with Join .

let str = 'abc defghijk lmnop qrstuv wx y z'

tokens = str.split(' ')

str = tokens[0] + ' ' + tokens.slice(1).join('')

console.log(str)

Explaining the code:

  • Separates the text into an array using the space character as a separator.
  • Get the first text plus 1 space and join the rest of the text without spaces.
  • 23.08.2018 / 20:31