javascript - 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
解决方案
可以使用 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'));
推荐阅读
- typescript - TypeScript 通用剩余参数到联合返回类型
- jquery - Boostrap Carousel slide issue when containing a form (Chrome issue)
- android - How to handle interface for onActivityResult Override Method
- migration - HttpResponse does not contain a definition for AddHeader, BufferedOutput and BinaryWrite
- javascript - 我无法将发布请求从反应表单发送到烧瓶服务器
- youtrack - YouTrack 中的隐藏/暂停问题
- c - C/ 从文件到数组的字符串数据。分段故障
- sql - sql server error = 当子查询跟随 =, !=, <, <= , >, >= 或当子查询用作表达式时,这是不允许的
- c++ - 如何使用openssl通过ocsp验证证书
- laravel-5 - 我想在数据库表中添加图像的名称,而不是图像的整个路径,我想使用 Factory 和 Seeds