Regex printable ascii plus newline and carriage return

I am writing a validator function in javascript for data entry. I have two conditions I need to test for.

Case 1: All printable ASCII characters between 32 and 126 Case 2: All printable ASCII characters between 32 and 126 plus carriage return and new line.

Here is my regex for Case 1:

/^(?=[ -~])[^rn]*$/

Is this suitable for Case 2?

/^(?=[n-~])[^131416-37]*$/

Answer

You can use

  1. ^[ -~]*$, this pattern matches any printable ASCII chars without carriage return and a line feed chars because they are simply out of this range.

See this regex demo.

  1. ^[ -~rn]*$ will do because -~ defines the range described above + a line feed and a carriage return.

See this regex demo.

Also, check the ASCII table codes to see what is included in the ranges above.