Home > Mobile >  Regex that validates there is space after a period in javascript
Regex that validates there is space after a period in javascript

Time:01-23

Consider the following strings:

  • I am happy.And I know it.
  • I am happy. And I know it.
  • I am happy.
  • I am happy

The rule is simple: There must be a space after the period. Only one of these should fail, I have tried:

  • new RegExp(/(\.\s|^)(?!\S)/)

The result is:

new RegExp(/(\.\s|^)(?!\S)/).test('I am happy.And I know it.')
false


new RegExp(/(\.\s|^)(?!\S)/).test('I am happy. And I know it.')
false


new RegExp(/(\.\s|^)(?!\S)/).test('I am happy.')
false


new RegExp(/(\.\s|^)(?!\S)/).test('I am happy')
false

Only the first one should fail. The rest should pass.

I think I am close, I just need to adjust it to say "Do we have a character/word anything after the period, if so - require a space"

Thoughts?

CodePudding user response:

just test for . followed by a word and negate

!(/\.\w/.test('I am happy.And I know it.'))

or . followed by non-whitespace and negate

!(/\.\S/.test('I am happy.And I know it.'))

CodePudding user response:

Have you consider testing for periods without spaces after them using the regex \.[^ ] e.g.

str = "I am happy."
!str.search(/\.[^ ]/)
true

CodePudding user response:

You could assert that there is not a dot present followed by a non whitespace character.

^(?!.*?\.\S)

See the matched positions at the regex 101 demo.

console.log(/^(?!.*?\.\S)/.test('I am happy.And I know it.'));
console.log(/^(?!.*?\.\S)/.test('I am happy. And I know it.'));

  • Related