0

I need a javascript regex that will not allow more than one line break or carriage return. One line break is OK, more than one should not be permitted. I have this which does not allow any, but I'm unable to modify it to allow only one line break?

^[^\n\r]*$

PixelPaul
  • 2,609
  • 4
  • 39
  • 70
  • 1
    Why don't you just replace multiple with one instead of throwing an error? – epascarello Jan 09 '17 at 19:01
  • Do some research on regular expressions; especially [quantifiers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#quantifiers). See if you can figure it out yourself. – Heretic Monkey Jan 09 '17 at 19:04
  • Do you want to disallow more than 1 consecutive line breaks or more than 1 line breaks anywhere? – anubhava Jan 09 '17 at 19:18
  • disallow more than 1 consecutive line break – PixelPaul Jan 09 '17 at 19:30
  • 1
    Then just look for `/(?:\r?\n){2}/` for detecting 2 consecutive line breaks – anubhava Jan 09 '17 at 19:35
  • Are you just trying to detect if a string value has more than one CRLF? Also, is this from text entered in a browser? All line endings should be CRLF (http://stackoverflow.com/questions/14217101/what-character-represents-a-new-line-in-a-text-area). A simple `str.indexOf()` will do in this case. – James Wilkins Jan 10 '17 at 03:07

3 Answers3

0

You can use match to text for multiple \n and throw an alert, like so:

var text = "hello\nworld\n\nmore here\n"

if (text.match(/\n[\n]+/g)){
  alert("Error mulitple new lines");  
}

You may want to first remove the \r or alter the above to also match \r also.

Phil Poore
  • 2,086
  • 19
  • 30
  • Ideally what I'm looking for is a regex to match the condition of more than one line break, where I will trigger an error message on form submission instead of a replace. – PixelPaul Jan 09 '17 at 19:12
  • i've updated the code and placed an `alert` where you will need to tie into your form errors. – Phil Poore Jan 09 '17 at 19:18
  • 2
    There's no need to put it inside `[]`. – Barmar Jan 09 '17 at 19:41
0

The round brackets constitute a group. Your group is "\n\r", which should not be multiple. So you use a "+", that constitute 1 or more. In following case it will replace every multiple "\n\r" with "\n\r\" and every single "\n\r" with it.

var multiple = "hello\n\r\n\rworld\n\r!"

var single = multiple.replace(/(\n\r)+/g, "\\n\\r");
console.log(single);
DomeTune
  • 1,401
  • 10
  • 21
0

Instead of looking for ^[\n\r]* look for ^\n\r[\n\r]*

var regpat = /^(\n\r)[\n\r]*/;
var str = "\n\r\n\r";
str.replace(re, '$1');