Detecting Line Break

Asked

Viewed 6,348 times

8

I have the following function:

  if (str.match(/\d\d\d\d\d\.\d\d\d\d\d/)) {
    var codigo_velho = str.match(/\d\d\d\d\d\.\d\d\d\d\d\/);
    result = "1"; }

How to change this function so it detects line break on match? For example, I tried with \n but it didn’t work out:

 if (str.match(/\d\d\d\d\d\.
                         \d\d\d\d\d/)) {
    var codigo_velho = str.match(/\d\d\d\d\d\.
                                       \d\d\d\d\d\/);
    result = "1"; }
  • Have you tested with the n expression inside the regex? Like: d d n d...? I know that breaking the line doesn’t work.

  • Tried to \r\n? Line break is half variable...

  • @Felipeavelar, tried r n did not work..

  • @Wakim, unfortunately did not. Because the code line that comes in MATCH, some of them jump line. type 222222 n222222, when it happens it does not detect.

4 answers

10

Do not use literal line breaks, use \n and a safeguard for the \r: \r?\n. This would work with Unix-style line breaks (\n) and Windows (\r\n). The part of match then it would look like this:

str.match(/\d\d\d\d\d\.\r?\n\d\d\d\d\d/)

Or shortening a little with the suggestion by Leonardo Bosquett:

str.match(/\d{5}\.\r?\n\d{5}/)
  • Why use the multiline flag in this case? As far as I remember, the flag m changes the behaviour of anchors ^ and $ to match'ar at the beginning and end of each line instead of the beginning and end of the string. Since you are not using these anchors, this flag should not make any difference.

  • You are right @Fabríciomatté. I will delete the answer, since without it the others already say everything that needs to be said.

  • 1

    Well, I wouldn’t rule her out \r?\n is not mentioned in any other answer, and is also my favorite form of match'ar line breaks. =]

  • Acatado @Fabríciomatté :) Editei.

6


The question has already been widely answered, so I will only make a suggestion, instead of using .match() to detect line breaks, use .test() to check whether or not the test content contains line breaks, something like this:

verificarQuebra = function()
{
  var valor = $('#div1').html();
  if (/[\n|\n\r]/.test(valor))  
  {
      alert("Existem quebras de linha!");
  } else
  {
      alert("Não existem quebras de linha!");
  } 
}

Demonstration aqui.


There is a difference between .match() and .test()?

The function .test() Search between a regular expression and a string specified. Returns true or false. Already .match() is used to obtain the results by combining a string against a regular expression. Returns a array with the results or void if there is none. Soon null == false if the string does not have a result, the boolean value will be false.

The MDN cites the following on:

If you need to know if a string corresponds to an expression regular, use Regexp.test(str).

Is there a significant difference in performance? According to Jsperf, yes, the difference is approximately 30% ~ 60% depending on the browser. Details taken dessa resposta.

inserir a descrição da imagem aqui

  • 1

    Nice response friend @DBX8!

4

Line breaking can have different formats. The best way to "catch" it is to be comprehensive in regex.

Suggestion: string.match(/(\r\n|\n|\r)/gm);

The selector \n is the essential. Worth reading this answer on differences between \n and \r. Then I used the g to return to me all the results, and not only the promise, and yet the m which means multiple-line. In the example I put down is not necessary but as I do not know exactly how you will use, I put.

Example in operation: http://jsfiddle.net/yL5Gk/

HTML

<div id="div1">Quebra de linha 1: 
    - continua aqui</div>
<div id="div2">Quebra. <br />Quebra. 





    Quebrão :)</div>
<div id="div3">Nenhuma quebra</div>

Javascript

var mensagem = '';
$('div').each(function () {
    var string = this.innerHTML;
    var linhas = string.match(/(\r\n|\n|\r)/gm);
    var quantidadeLinhas = linhas ? linhas.length : 0;
    mensagem += 'A div ' + this.id + ' tem ' + quantidadeLinhas + ' quebras de linha\n';
});
alert(mensagem);

The Alert that this gives is:

Div div1 has 1 line breaks
Div div2 has 6 line breaks
Div div3 has 0 line breaks

2

the line breaking test in Javascript by Regex is n as Wakin said, see the test in the Chrome console:

inserir a descrição da imagem aqui

if you have problems with line breaks in different versions of S.o try this:

var newExpression = expression.replace("\r\n", "\n");

Or simply remove them from validation if they are not necessary:

var newExpression = expression.replace("\r\n", "");

Tip: expressions like d d d d can be simplified by [\d]{4}

I index this site also to test your regular expressions: http://regexpal.com/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.