Search code examples
javascriptregexvue.jsregexp-replace

Regex replace "\n" occurrences by divide by 2


I have string with \n

First\nSecond\n\nThird\n\n\n\n

I want after replace (\n >=2), it's

First\nSecond\nThird\n\n

I would appreciate some help. Many thanks!


Solution

  • Just replace every two \n with a single \n:

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

    const s = 'First\nSecond\n\nThird\n\n\n\n'
    
    console.log(JSON.stringify(s.replace(/\n\n/g, '\n')))