Search code examples
javascriptregexwhitespace

Limit more than one linebreak, limit double space, RegEx replace


I'm having trouble limiting a string to prevent multiple spaces and multiple linebreaks. This reformat is gonna happen to an input value before uploading to server.

Ex:

Input:

    i am    a   text
with

little



to no


meaning    asdas

Expected output:

i am a text
with

little

to no

meaning asdas

I googled this but it only helps with linebreaks.

str.replace(/\n\s*\n/g, '\n\n')

Solution

  • Using \s can also match a newline. Instead you can use a negated character class to match a whitespace character without a newline [^\S\n]

    You could:

    • Trim the string

    • Match 2 or more newlines followed by whitespace chars without newlines using ^(?:\n[^\S\n]*){2,} and replace with a single newline

    • Match 2 or more whitespace chars without a newline [^\S\n]{2,} and replace with a single space.

    const s = `    i am    a   text
    with
    
    little
    
    
    
    to no
    
    
    meaning    asdas`;
    const result = s.trim()
      .replace(/^(?:\n[^\S\n]*){2,}/gm, "\n")
      .replace(/[^\S\n]{2,}/g, " ");
    
    console.log(result);