JavaScript Program to Check if String Follows Order of Characters Defined by a Pattern or Not Last Updated : 27 May, 2024 Comments Improve Suggest changes Like Article Like Report In this JavaScript article, we will see the solution to the problem of checking if a string follows the order of characters defined by a pattern or not. We have given a string and pattern as the input and our task is to develop a program that will check whether the input string follows the same pattern according to the pattern given. Example: To solve this problem, we have three different approaches which are mentioned below: Table of Content Using JavaScript LoopsUsing JavaScript MapUsing Builtin Functions 'every', 'reduce', and 'split' Using Regular Expression:Using JavaScript LoopsIn this apporach, we are using the looping in JavaScript, where we are comparing the order of the chatacter occurences between the input pattern and the input string. We are iterating thorugh them, and also having a track of max and min indexes of he chatacter occurences. If the patterm's characters order is matched in the input string's order then the true result is returned else the false result will be returned. Examples: JavaScript function checkPattern(str, pattern) { // lcmi -> Last char max index // ccmi -> current char max index // ccmin -> current char min index let lcmi = -1, ccmi = -1, ccmin = -1; let matchValue = true; lcmi = lastOcc(str, pattern[0]); for (i = 1; i < pattern.length; i++) { ccmi = lastOcc(str, pattern[i]); ccmin = firstOcc(str, pattern[i]); if (lcmi < ccmi && lcmi < ccmin) { matchValue = true; } else { matchValue = false; } lcmi = ccmi; if (matchValue == false) break; } return matchValue; } function lastOcc(str, chr) { let currentIdx = 99999999, maxIdx = -1; for (j = 0; j < str.length; j++) { if (chr == str[j]) { currentIdx = j; if (currentIdx > maxIdx) maxIdx = currentIdx; } } return maxIdx; } function firstOcc(str, chr) { let currentIdx = 99999999, minIndex = 999999999; for (k = 0; k < str.length; k++) { if (chr == str[k]) { currentIdx = k; if (currentIdx < minIndex) minIndex = currentIdx; } } return minIndex; } console.log(checkPattern("engineers rock", "er")); console.log(checkPattern("engineers rock", "egr")); console.log(checkPattern("engineers rock", "gsr")); Outputtrue false false Using JavaScript MapIn this apporch, we are using the Maps in JavaScript where we have used the two map objects (map1 and map2).This objects establish the connection between the chacraters in the input pattern and words in the input string, as well as the reverse mapping. This assures that the mappings are proper and returns true if the character and words are aligned correctly else false will be returned. Examples: JavaScript function checkPattern(str, pattern) { let words = str.split(' ') if (pattern.length !== words.length) return false let map1 = new Map(); let map2 = new Map(); for (let i = 0; i < pattern.length; i++) { let key = pattern[i]; let value = words[i]; if (map1.has(key) || map2.has(value)) { if (map1.get(key) !== value) return false; if (map2.get(value) !== key) return false; } else { map1.set(key, value); map2.set(value, key); } } return true; }; console.log(checkPattern("engineers rock", "er")); console.log(checkPattern("engineers rock", "egr")); console.log(checkPattern("engineers rock", "gsr")); Outputtrue false false Using Builtin Functions 'every', 'reduce', and 'split'In this apporach we are using inbuilt fucntions rather than using complex data structures.We firslty split the input string into words and then by using reduce funtion we create a mapping between pattern chatacters and the corresposnding words. Lastly, we check if all the mapped values are aligned properly witht he words in the input string using the every function.If they are aligned properly then true result will be returned else false result will be returned. Example: JavaScript function checkPattern(str, pattern) { let words = str.split(" "); if (words.length !== pattern.length) { return false; } let patternToWord = pattern.split("").reduce((map, character, index) => { if (!map.has(character)) { map.set(character, words[index]); } else if (map.get(character) !== words[index]) { return false; } return map; }, new Map()); let values = [...patternToWord.values()]; let ans = values.every((value, index) => value === words[index]); return ans; } console.log(checkPattern("engineers rock", "er")); console.log(checkPattern("engineers rock", "egr")); console.log(checkPattern("engineers rock", "gsr")); Outputtrue false false Using Regular Expression:Using Regular Expression: Create a RegExp pattern by joining characters from the input pattern with '.*', representing any character zero or more times. Test if the string matches the pattern anchored at both ends. Example: In this example The function followsPattern utilizes a regular expression to match if the string str follows the character order defined by pattern, returning true for a match and false otherwise JavaScript function followsPattern(str, pattern) { const regex = new RegExp('^' + pattern.split('').join('.*') + '$'); return regex.test(str); } const str1 = "abc"; const pattern1 = "abc"; console.log(followsPattern(str1, pattern1)); const str2 = "xyz"; const pattern2 = "xzy"; console.log(followsPattern(str2, pattern2)); Outputtrue false Comment More infoAdvertise with us Next Article JavaScript Program to Check if String Follows Order of Characters Defined by a Pattern or Not G gauravgandal Follow Improve Article Tags : JavaScript Web Technologies Geeks Premier League javascript-string JavaScript-DSA JavaScript-Program Geeks Premier League 2023 +3 More Similar Reads JavaScript Program to Validate String for Uppercase, Lowercase, Special Characters, and Numbers In this article, we are going to learn how can we check if a string contains uppercase, lowercase, special characters, and numeric values. We have given string str of length N, the task is to check whether the given string contains uppercase alphabets, lowercase alphabets, special characters, and nu 4 min read Javascript Program to Check if a given string is Pangram or not In this article, we are going to implement algorithms to check whether a given string is a pangram or not. Pangram strings are those strings that contain all the English alphabets in them.Example: Input: âFive or six big jet planes zoomed quickly by tower.â Output: is a Pangram Explanation: Does'not 7 min read Java Program to Check Whether the String Consists of Special Characters In Java, special characters refer to symbols other than letters and digits, such as @, #, !, etc. To check whether the String consists of special characters, there are multiple ways, including using the Character class, regular expressions, or simple string checks.Example:In this example, we will us 4 min read Java Program to Sort an Array of Strings in Lexicographical Order (Dictionary Order) In Java, sorting an array in lexicographical (dictionary) order means elements will be arranged based on their alphabetical order from A to Z with case sensitivity.Example:We will use Arrays.sort() method with String.CASE_INSENSITIVE_ORDER to sort an array in lexicographical order. It is the most di 3 min read How to Check if a String Contains Only Lowercase Letters in Java? A string is a data structure that contains a set of characters. It can be a word or can be a sentence. Also, it can be empty or can have a single letter. A string can contain Uppercase letters, Lowercase letters, or numbers of special characters. In this article, we will learn how to check if a Stri 4 min read How to Convert a Java String Against a Pattern Regex? Regular expressions, or "regex," are an effective tool in Java programming for checking texts against a given pattern. This post will walk you through the process of utilizing regular expressions to validate a Java text against a pattern. Prerequisites:String in JavaRegular Expressions in JavaConver 2 min read How to Check if a String contains only ASCII in Java? The full form of ASCII is the American Standard Code for Information Interchange. It is the numeric representation of Character. As Java supports multiple languages, and it follows the Unicode system. In simple terms for better understanding, it converts the Character to a specific unique number, an 3 min read How to Check if a String Starts With One of Several Prefixes in Java? Java programming provides a lot of packages for solving real-time problems. In our case, we need to check if a given string starts with one of several prefixes. For This first, we need to take one String value after that take some prefixes for testing if the String starts with one of several prefixe 2 min read Check if two strings are permutation of each other Write a function to check whether two given strings are Permutation of each other or not. A Permutation of a string is another string that contains same characters, only the order of characters can be different. For example, "abcd" and "dabc" are Permutation of each other. We strongly recommend that 13 min read Compare Strings for equality or lexicographical order in different programming Languages Given two strings string1 and string2, the task is to check if these two strings are equal or not. Examples: Input: string1 = âGeeksforGeeksâ, string2 = âGeeksforGeeksâ Output: Yes Input: string1 = âGeeks for Geeksâ, string2 = âGeeks for Geeksâ Output: Yes Input: string1 = âGeeksforGeeksâ, string2 = 8 min read Like