I am trying to test the string, either it contains the first letter of word are capital letter. but not getting result.
please correct me.
here is my code:
const str = "This Is How it";
const patten = /\b(^[A-Z])\w \b/g;
console.log(patten.test(str));
Actually it should give false
but getting true
. because last word it
not start with capital.
CodePudding user response:
If you need to check a line if all the words inside it begin with a capital letter, here is one way to do it:
CodePudding user response:
.split(' ')
the string at each space.- Run the array through
.every()
- In each iteration of
.every()
,.test()
each word vs./\b[A-Z][a-z]*\b/
- If all words pass then
true
is returned elsefalse
is.
const title1 = "The Empire Strikes Back";
const title2 = "The Return of the Jedi";
function firstLetterCap(string) {
const rgx = /\b[A-Z][a-z]*\b/;
return string.split(' ').every(word => rgx.test(word));
}
console.log(firstLetterCap(title1));
console.log(firstLetterCap(title2));