简体   繁体   中英

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!!!

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() .

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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM