0

I'm checking whether character is capital letter or not by using javascript RegExp

function splitWords(text) {
    const capReg = /[A-Z]/g;
    const alphaNumReg = /[a-z0-9]/g;

    for (let i = 0; i <= text.length - 1; i++) {
        console.log(
            text[i], text[i + 1], text[i + 2], 
            capReg.test(text[i]), capReg.test(text[i + 1]), 
            alphaNumReg.test(text[i + 2])
        );
    }
}
splitWords('ABCOption');

at case expected C, O, p, true, true, true Actual C, O, p, true, false, true

Please help me where i'm doing wrong

  • i cannot explain it well but i know that the behavior of test() is not as expected. I use https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/String/match for testing for occurances. similar, but you ask the string for to match the regexp and not the aother way around. – Paulquappe Jan 04 '19 at 13:24

3 Answers3

1

This is how you can get array and check every capital letter:

const res = Array.from("ABCOption").map(e=>/[A-Z]/.test(e));

console.log(res)
Vadim Hulevich
  • 1,803
  • 8
  • 17
  • +1 for this great solution, but it would be stronger if you use `const res = Array.from(text).map(e => e === e.toUpperCase());`, so it will also recognize foreign upper case letters, like Ñ. Cannot imagine why OP accepts the other answer though. – evayly Jan 04 '19 at 13:38
  • @evayly If you're refering to the previous selected answer, my guess is that the code was the same as his own (except for the working regex) and/or the OP does not know ES6 syntax and couldn't figure out how to implement his function inside ES6 arrow functions. If you're talking about mine, it contains a working regex and a link to implement a split function in a cleaner way than what he was going to do. – Carrm Jan 07 '19 at 16:09
1

the below code worked for me hope work for you also. you just have to change your regex like below

function splitWords(text) {
        const capReg = /^[A-Z]*$/;// /[A-Z]/g just replace your regexp and try ;
        const alphaNumReg = /^[a-z0-9]*$/;// /[a-z0-9]/g ;

        for (let i = 0; i <= text.length - 1; i++) {
            console.log(
                text[i], text[i + 1], text[i + 2],
                capReg.test(text[i]), capReg.test(text[i + 1]),
                alphaNumReg.test(text[i + 2])
            );
        }
    }
Jasmin Raval
  • 184
  • 1
  • 5
  • 15
0

You don't need the g part in your regex if you're checking character by character; g is used when you don't want to stop at the first match. Just replace your regex by /[A-Z]/ and it will work as expected.

Moreover, if you want to split a string into words based on uppercased letters, you can do it directly with patterns. Check this SO question to see some solutions

Carrm
  • 1,485
  • 3
  • 24
  • 45