javascriptstring

Search within a string and stops immediately at the first found


I'm working with CSV files and need to check newline character.

This function works fine:

function detectNewlineCharacter(csvContent)
{
  if (csvContent.includes('\r\n')) {
    return '\r\n'; // Windows-style CRLF
  } else if (csvContent.includes('\n')) {
    return '\n'; // Unix-style LF
  } else if (csvContent.includes('\r')) {
    return '\r'; // Old Mac-style CR
  } else {
    return null; // No recognizable newline characters found
  }
}

function fixCsv()
{
  // ...code...
  const newlineCharacter = detectNewlineCharacter(fileContent);
  const rows = fileContent.split(newlineCharacter);
  // ...code...

}

Problem:

csvContent is very large. I need a method that stops immediately at the first found, just like .some() for array. ChatGPT said .includes() stops at the first found, but I'm not sure, can't find that in the documentation. So does .match(), .indexOf(), etc.

My last resort would be to limit the string using .substring() before searching.

EDIT:

Answers from another possible-duplicate questions do not address the actual problem in this question. I'm not looking for a way to detect line break. As the title of this question clearly stated that I'm looking for a method which stops searching the string immediately after it found a match. It just happen that detecting line break is part of the codeflow.


Solution

  • Here is a function that stops after finding the first newline of any type, using a regular expression:

    function detectNewlineCharacter(csvContent)
    {
      return /\r\n|\n|\r/.exec(csvContent)?.[0] ?? null;
    }
    

    Test cases:

    detectNewlineCharacter('') === null
    detectNewlineCharacter('ABC\r\nDEF') === '\r\n'
    detectNewlineCharacter('A\nB\r\nC') === '\n'
    detectNewlineCharacter('AB\rCD\nEF\r\n') === '\r'