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

137
Views
How to make the following regex match and replace unclosed double quotes?

The following code replace straight double quotes with curly double quotes:

 const input = `"Line 1"

"Line 2

"Line 3"

Line 4`
 
const output = input.replace(/\"(.*?)(\")/g, '“$1”')
 
console.log(output)

There's a problem, though. Sometimes a line doesn't have a closing double quote (which indicates that the quotes continues on the line below). So the opening double quote won't be replaced:

`“Line 1$1”

"Line 2

“Line 3$1”

Line 4`

How to modify the regex so it also replaces opening double quotes that aren't followed by a closing double quote?

Desired output:

`“Line 1$1”

“Line 2

“Line 3$1”

Line 4`
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

I would go in 2 successive replace(), if it's ok:

  • one for caching the "...'" form
  • another for catching the remaining "...
const output = input
    .replace(/\"(.*?)(\")/g, '“$1”')
    .replace(/\"(.*)/g, '“$1”')

But I didn't understand if you wanted to match multilines results in an unique final string, or just add quotes to the end of each line

about 4 years ago · Juan Pablo Isaza Report

0

  1. List item

const input = `"Line 1"

    "Line 2

    "Line 3"

    Line 4`
     
      const output = input.replace(/"([^"/]*)"/g, '“$1”')

     
    console.log(output)

about 4 years ago · Juan Pablo Isaza Report

0

You can use

.replace(/^"([^"\n\r]*)"?$/gm, "“$1”")

See the regex demo. The regex matches all non-overlapping occurrences (g), while matching start of lines with ^ and end of lines with $ (due to m) and means

  • ^ - start of a line
  • " - a double quotation mark
  • ([^"\n\r]*) - Group 1: any zero or more chars other than ", CR and LF
  • "? - an optional " char
  • $ - end of any line.

See the JavaScript demo:

 const input = `"Line 1"

"Line 2

"Line 3"

Line 4`
 
const output = input.replace(/^"([^"\n\r]*)"?$/gm, '“$1”')
 
console.log(output)

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!