ajinkyah
ajinkyah

Reputation: 111

CR, LF and CRLF characters in a String

Is it safe to assume that a string will at any time only have either CR, LF or CRLF for a line break?

I want to write a logic to replace all the LF characters with CRLF characters in JavaScript but I have to this doubt.

I was thinking I can find all the LF (\n), check if it doesn't have CR(\r) before it and then replace the \n with \r\n.

If anyone has done this, please suggest what is the best way to do it?

Upvotes: 1

Views: 22299

Answers (2)

Gajender Singh
Gajender Singh

Reputation: 1313

Use can use replace method it'll automatically check if match string is there then replace that with an argument.

   var data = "LFSingh";
   data = data.replace("LF","CRLF");
   console.log(data);

Upvotes: -1

Limbo
Limbo

Reputation: 2290

AFAIK, the \r symbol standalone is never used to make a line-break. It can be \n or \n\r. In this case, you can use a regular expression /\n\r?/g to replace all possible linebreaks:

var someString = "kappa\npride\n\rgreyFace"
var lfcrRegexp = /\n\r?/g
var result = someString.replace(lfcrRegexp, "whatever") // => kappawhateverpridewhatevergreyFace

Upvotes: 3

Related Questions