首页 > 解决方案 > Check if string contains 3 or more ordered characters in javascript (no regex)

问题描述

Looking for code that can detect if the string has repeating characters (sss, 333, !!!) And/or also if it contains subsequent characters in order such as (345, efg, abc, 789)

I know their exist ways to do it with regex but wanted to know if any algorithm exist that does it with just loops

const str="abc123";
//loop through char to determine if it contains subsequent characters like abc...
 //str should return true
//loop through char to determine if it contains repeated characters like bbb...
 //str should return false

标签: javascriptnode.jsstringloops

解决方案


可以使用 JavaScript 提供的 charCodeAt 函数。您需要遍历字符串并比较它是重复字符还是有序字符。

这是Codepen链接。

var str = "abc123";

str = str.toLowerCase();
var len = str.length;
var a = str.charCodeAt(0);

var n = 3;

var isRepeatingCharFound = false;
var isOrderedCharFound = false;
for (var i = 0; i < str.length; i++) {
    if (i + (n - 1) <= len) {

        var isRepeatingCharFoundTmp = false;
        var isOrderedCharFoundTmp = false;
        for (var j = i; j < i + n; j++) {
            if (str.charCodeAt(i) === str.charCodeAt(j))
                isRepeatingCharFoundTmp = true;
            else
                isRepeatingCharFoundTmp = false;

            if (str.charCodeAt(i) === str.charCodeAt(j) - (n - 1))
                isOrderedCharFoundTmp = true;
            else
                isOrderedCharFoundTmp = false;
        }
        if (isRepeatingCharFoundTmp)
            isRepeatingCharFound = true;
        if (isOrderedCharFoundTmp)
            isOrderedCharFound = true;
    }
}
console.log('Repeating char ' + (isRepeatingCharFound ? 'found' : 'not found'));
console.log('Ordered char ' + (isOrderedCharFound ? 'found' : 'not found'));


推荐阅读