Using only replace
can also be done, although it probably does not compensate 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
See this regex in regex101
So you can read this regex as capturing a space that has another space behind followed by anything. For this reason you will not catch the first because it has no back space.
It is worth remembering that this uses Positive lookbehind, which was added to javascript a short time ago and so is likely not to work in older browsers. The second note is that this is a lookbehind of a variable size than most regex Engines of other languages and does not 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 really do the simple and use a indexOf
as suggested to get the first space and replace from there.
You want to go back to string like it was?
– Wees Smith
No, I want to remove all bad spaces by preserving the first
– Lauro Moraes