Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

156
Views
How to remove duplicate \n (line break) from a string and keep only one?

I have a string like this:

This is a sentence.\n This is sentence 2.\n\n\n\n\n\n This is sentence 3.\n\n And here is the final sentence.

What I want to is:

This is a sentence.\n This is sentence 2.\n This is sentence 3.\n And here is the final sentence.

I want to remove all duplicated \n characters from a string but keep only one left, is it possible to do like that in javascript ?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You may try replacing \n{2,} with a single \n:

var input = "This is a sentence.\n This is sentence 2.\n\n\n\n\n\n This is sentence 3.\n\n And here is the final sentence.";
var output = input.replace(/\n{2,}\s*/g, '\n');
console.log(output);

about 4 years ago · Juan Pablo Isaza Report

0

You can use regex as /\n+/g to replace it with single \n

enter image description here

const str =
  "This is a sentence.\n This is sentence 2.\n\n\n\n\n\n This is sentence 3.\n\n And here is the final sentence.";
const result = str.replace(/\n+/g, "\n");
console.log(result);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!