avinashr
avinashr

Reputation: 1

Regular Expression to validate on continuous character or numbers in JavaScript?

I need to validate if the string presents like continuous characters say like abc, def, ghi or 123,234,345,456 and so on using JavaScript, wants to through error or alert message. Is there any possibilities with Match Patterns or Expression to validate such scenario. Please if any come across, let me know asap.

Thanks in Advance!!!

Upvotes: 0

Views: 996

Answers (2)

Sergiu Toarca
Sergiu Toarca

Reputation: 2749

Regular expressions should not be used for this. They don't "have memory", which means that you can't look for such sequences dynamically. Instead you would have to construct every possible acceptable sequence manually.

A better idea would be to use a for loop to run through your string and make the necessary assertions, like so:

for (var i = 0; i < str.length; ++i) {
    if (str.charCodeAt(i) === str.charCodeAt(i + 1) - 1 &&
        str.charCodeAt(i) === str.charCodeAt(i + 2) - 2) {
        var ret = str.substr(i, i + 3);
        // do whatever you want to do with the match
    }
}

Upvotes: 0

DocMax
DocMax

Reputation: 12164

A regular expression is not the way to go for this one. Better will be to loop through all the characters in string checking if each is one greater than the last using str.charCodeAt().

Upvotes: 1

Related Questions