Aleksander Karp
Aleksander Karp

Reputation: 51

RegEx find newline between double quotes and replace with space

I need help to replace a newline with space in a string with double quotes and value between.

This is my current expression but it's only replace newline if string doesn't contain any other value.

/"([\r\n]*?)"/g

I want to change this:

For this:

Upvotes: 2

Views: 4364

Answers (3)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626754

To remove all chunks of line break chars in between double quotation marks, you need to match these substrings between the qualifying start and end double quotation marks. Thus, it is crucial to know if " chars can appear escaped in between the " delimiters.

In a CSV, the literal double quotation marks are usually doubled. Then, you may use

var s = '"Cell1","Cell\r\n#2","""Cell #3\r\nhere\nand there"""';
s = s.replace(/"(?:""|[^"])+"/g, function(x) { return x.replace(/[^\S\r\n]*[\n\r]\s*/g, ' ');});
console.log(s);

The "(?:""|[^"])+"/g regex matches a ", then 1 or more occurrences of "" substring or any char other than ", and then ". When the match is found, all CR and LF symbols with any 0+ whitespaces before and after them are removed using a simple .replace(/[^\S\r\n]*[\n\r]\s*/g, ' ') replace operation.

If the literal double quotation marks are escaped with a backslash, you may use

/"[^"\\]*(?:\\[\s\S][^"\\]*)*"/g

If you are sure there are no escaped double quotation marks, use

/"[^"]+"/g

Upvotes: 3

Jan
Jan

Reputation: 43169

You could use a function within .replace() like this:

var data = `
I need help to replace a newline with space in a string with double quotes and value between.

This is my current expression but it's only replace newline if string doesn't contain any other value.

I want to change this:

    "Log field with multiple lines.

    This is now fixed."

For this:

    "Log field with multiple lines. This is now fixed."
`;

var regex = /"[^"]*"/g;

data = data.replace(regex, function (match, capture) { 
    return match.replace(/[\n\r]\s*/g, " ");
}); 
console.log(data);

First, it looks for anything bewteen dobule quotes, second is removes newlines and possible consecutive whitespaces thereafter. The approach won't work with escaped quotes though.

Upvotes: 2

Faraz Kelhini
Faraz Kelhini

Reputation: 3985

This should solve your problem:

/\r\n|\r|\n/g

1st Alternative \r\n

\r matches a carriage return (ASCII 13) \n matches a line-feed (newline) character (ASCII 10)

2nd Alternative \r

\r matches a carriage return (ASCII 13)

3rd Alternative \n

\n matches a line-feed (newline) character (ASCII 10)

g modifier

All matches (don't return after first match)

Upvotes: 1

Related Questions