-1

I want to validate a string if it does not contain a new line.

for Eg: string 1: "adsfasdfasdf" - should say true

string 2: "asdfasdfsd

asdfasdfas" should return false (i don't want string which has a new line)

string 3: "asdf efgh" should say true (string has space needed, need to ignore if it has new line or tab)

my regex - /^\S+$/ // this consider tab along with new line... I tried \N but no help... I want to validate the new line, not tab space.

const regE = new RegExp(/^\S+$/g);
console.log("working", regE.test("Asdfasdf"));
console.log("working", regE.test("asdfasd\n\n\nasdf"));
console.log("not working", regE.test("Asdfasasdfsa dfasdfsdfd"));
Mohideen bin Mohammed
  • 14,471
  • 7
  • 86
  • 95

2 Answers2

0

I think this is what you are looking for: /^[^\r\n\f\v]+$/g

\S is equal to [^\r\n\t\f\v ]. So you only need to remove the \t which is for tab and the whitespace.

You can see the explanations at the right on this example: https://regex101.com/r/cc1Hu8/1

Sebastian
  • 996
  • 1
  • 9
  • 16
0

I added a match group around your "any non-whitespace char" and added a space to that again.

^    //start of line
 [   //start group
  \S //match any non-whitespace character
  .  //match character except new line
 ]+  //match group one or more times
 $   //end of line

const regE = new RegExp(/^[\S.]+$/g);
console.log("Should be true, it is", regE.test("Asdfasdf"));
console.log("Should be false, it is", regE.test("asdfasd\n\n\nasdf"));
console.log("Should be true, it is", regE.test("Asdfasasdfsa dfasdfsdfd"));
Misantorp
  • 1,868
  • 1
  • 7
  • 16