Regular expression to check if all words have a title

I am trying to find a regex to verify the following:

This Is A Cat

However, to evaluate the following, to be false:

This Is A Cat

Or this is also not true:

This Is A cat (Note the 'c' is not upper case in Cat)

I am trying to use JavaScript, believing that the following should work:

/(\b[A-Z][a-z]*\s*\b)+/

Here is my logic:

  • Start with the word boundary
  • Matches an uppercase character
  • Matches zero or lowercase characters
  • Match zero or more spaces
  • Match Word Border
  • Repeat the above one or more times

What is wrong with my thinking?

-1
source share
3 answers

What is wrong with my thinking?

You find a sequence of words with a table of contents, but this will not perceive cases where there are words without a name.

, :

const tests = ['This Is A Cat', 'This is a cat', 'This Is A cat'];

// Is there any occurrence of a word break followed by lower case?
const re = /\b[a-z]/;

tests.forEach(test => console.log(test, "is not title case:", re.test(test)));
Hide result

, , , (.. "" ):

const tests = ['This Is A Cat', 'This is a cat', 'This Is A cat'];

// Is the entire string a sequence of an upper case letter,
// followed by other letters and then spaces?
const re = /^\s*([A-Z]\w*\s*)*$/;

tests.forEach(test => console.log(test, "is title case:", re.test(test)));
Hide result

?

, , , . :

const re = /^\s*[A-Z]\w*\s*(a|an|the|and|but|or|on|in|with|([A-Z]\w*)\s*)*$/;
+1

, g .

g ,

:

/(\b[A-Z][a-z]*\s*\b)+/g
0

If you want to find out if the string matches the condition and does not care where it happens, you can check either the lowercase letter at the beginning of the line or the lowercase letter that follows the space

var str = 'This Is A Cat';
if (str.match(/\b[a-z]/)) {
  console.log('Not Title Case');
}

var str2 = 'This is A Cat';
if (str2.match(/\b[a-z]/)) {
   console.log('Example 2 Is Not Title Case');
}

var str3 = 'this Is A Cat';
if (str3.match(/\b[a-z]/)) {
   console.log('Example 3 Is Not Title Case');
}
Run codeHide result
0
source

Source: https://habr.com/ru/post/1687037/


All Articles