skip to Main Content

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(/ns*n/g, 'nn')

2

Answers


  1. First replace more than 2 newlines with exactly 2 newlines, then replace multiple spaces with a single space?

    var t = `
    i am    a   text
    with
    
    little
    
    
    
    to no
    
    
    meaning    asdas
    `.trim();
    console.log(t.replace(/n{2,}/g, 'nn').replace(/[ ]{2,}/g, ' '));
    Login or Signup to reply.
  2. Using s can also match a newline. Instead you can use a negated character class to match a whitespace character without a newline [^Sn]

    You could:

    • Trim the string

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

    • Match 2 or more whitespace chars without a newline [^Sn]{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[^Sn]*){2,}/gm, "n")
      .replace(/[^Sn]{2,}/g, " ");
    
    console.log(result);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search