Regex replace linebreak and comma

3.1k Views Asked by At

i've a question about regex, i've a text and it looks like below :

car,model,serie
,Mercedes,324,1,
,BMW,23423,1,
,OPEL,54322,1,

it should look like:

car,model,serie
Mercedes,324,1,
BMW,23423,1,
OPEL,54322,1,

so without commas at the beginning of the text.

What i tried :

var str2 = str.replace(/\n|\r/g, ""); 

but somehow, i couldn't add comma in regex.

can anyone help me? Thanks in advance.

4

There are 4 best solutions below

1
On BEST ANSWER

There have been a lot of responses to this question and for a newbie to regex it is probably a bit overwelming,

Overall the best response has been:

var str2 = str.replace(/^,/gm, '');

This works by using ^, to check if the first character is a comma and if it is, remove it. It also uses the g and m flags to do this for the first character of every line.

If you are curious about the other versions then read on:

1:

var str2 = str.replace(/^,+/gm, '');

This is a slight variant in that it will remove multiple consecutive commas at the beginning of each line, but based off of your dataset this is not required.

2:

var str2 = str.replace(/\n,/g, '\n');

This version works exactly the same as the first, however it finds each newline follow by a comma with \n, and replaces it with another newline.

3:

var str2 = str.replace(/(\n|\r),/g, '$1')

This version is the same as the previous however it doesn't make the assumption that the newline is a \n, it instead captures any newlines or carriage returns, it works the same as the m flag and ^,.

4:

var str2 = str.replace(/\n+|\r+|,+/g,"\n")

And finally there is this, this is a combination of all the previous regex's, it makes the assumption that you may have a lot mixed newlines and commas without any text, and that you would want to remove all of those characters, it is unnecessary for your examples.

2
On

Try:

var str2 = str.replace(/(\n|\r),/g, '$1')

Your comma was actually placed outside the regex pattern, so you weren't far off :)

0
On

Use this syntax:

str.replace(/^,/gm, '');
0
On

You can just use multiline flag and replace leading commas:

str = str.replace(/^,+/gm);

RegEx Demo