使用 JavaScript 根据单词数组验证字符串
问题
我们需要编写一个 JavaScript 函数,该函数需要接收一系列有效单词和一个字符串。我们的函数应测试字符串是否由该数组的一个或多个单词组成。
输入
const arr = ['love', 'coding', 'i']; const str = 'ilovecoding';
输出
const output = true;
因为字符串可以由数组 arr 中的单词组成。
示例
以下为代码 −
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));输出
true
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP