Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Validating string with reference to array of words using JavaScript
Problem
We are required to write a JavaScript function that takes in a sequence of valid words and a string. Our function should test if the string is made up by one or more words from the array.
Input
const arr = ['love', 'coding', 'i']; const str = 'ilovecoding';
Output
const output = true;
Because the string can be formed by the words in the array arr.
Example
Following is the code −
const arr = ['love', 'coding', 'i'];
const str = 'ilovecoding';
const validString = (arr = [], str) => {
let arrStr = arr.join('');
arrStr = arrStr
.split('')
.sort()
.join('');
str = str
.split('')
.sort()
.join('');
const canForm = arrStr.includes(str);
return canForm;
};
console.log(validString(arr, str));
Output
true
Advertisements