- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to write a JavaScript function that returns true if a portion of string 1 can be rearranged to string 2?
We have to write a function that returns true if a portion of string1 can be rearranged to string2. Write function, say scramble(str1,str2) that returns true if a portion of str1 characters can be rearranged to match str2, otherwise returns false.
For example −
Let’s say string1 is str1 and string2 is str2. str1 is 'cashwool' and str2 is ‘school’ the output should return true. str1 is 'katas' and str2 is 'steak' should return false.
So, here is the code for doing this. We simply split and sort the two strings and then check whether the smaller string is a substring of the larger one or not.
The full code for doing so will be −
Example
const str1 = 'cashwool'; const str2 = 'school'; const scramble = (str1, str2) => { const { length: len1 } = str1; const { length: len2 } = str2; const firstSortedString = str1.split("").sort().join(""); const secondSortedString = str2.split("").sort().join(""); if(len1 > len2){ return firstSortedString.includes(secondSortedString); } return secondSortedString.includes(firstSortedString); }; console.log(scramble(str1, str2));
Output
The output in the console will be −
true
- Related Articles
- Can part of a string be rearranged to form another string in JavaScript
- Check if a string can be rearranged to form special palindrome in Python
- Check if characters of a given string can be rearranged to form a palindrome in Python
- Write a function that returns 2 for input 1 and returns 1 for 2 in C programming
- How can we check that by default MySQL CHAR() function returns a binary string?
- Write a program in Java to check if a string can be obtained by rotating another string by 2 places
- How to use JavaScript to replace a portion of string with another value?
- Checking if a string can be made palindrome in JavaScript
- Write a program in C++ to check if a string can be obtained by rotating another string by two places
- MySQL query that returns a specific string if column is null?
- Check if a string can be repeated to make another string in Python
- How to return a string from a JavaScript function?
- How to check if a string can be converted to float in Python?
- Function to reverse a string JavaScript
- Check if a string can be obtained by rotating another string 2 places in Python

Advertisements