Yaswanth Goli
Yaswanth Goli

Reputation: 13

RegExp test function odd behavior

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

Upvotes: 0

Views: 54

Answers (3)

Carrm
Carrm

Reputation: 1593

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

Upvotes: 0

Jasmin Raval
Jasmin Raval

Reputation: 304

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])
            );
        }
    }

Upvotes: 1

Vadim Hulevich
Vadim Hulevich

Reputation: 1833

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)

Upvotes: 1

Related Questions